gpt4 book ai didi

.net - 在 using 语句中调用 Task.Run 可以吗?

转载 作者:行者123 更新时间:2023-12-02 06:00:43 29 4
gpt4 key购买 nike

像这样的代码,我想将大部分工作放在 Task.Run 中,但我不确定 using 语句是否仍然按预期工作。

using(MemoryStream ms = new MemoryStream())
{
Task.Run(() =>
{
/* capture ms and process the stream */
}
} // Will ms will be disposed here automatically?

谢谢。

最佳答案

否 - 流处理可能会在您的任务完成运行之前运行。如果可以的话,您最好将使用放在任务中,或者在任务结束时手动处理处置。

var ms = new MemoryStream();
Task.Run(() =>
{
/* capture ms and process the stream */

// Dispose of the stream manually when you are done
ms.Dispose();
}

请注意,如果您在任务之外使用内存流,那么您将面临在释放内存流后使用它的风险。如果可以的话,只使用任务内部的流并将结果保存到其他地方。

Task.Run(() =>
{
using(var ms = new MemoryStream())
{
/* capture ms and process the stream */
}
}

关于.net - 在 using 语句中调用 Task.Run 可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40620802/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com