gpt4 book ai didi

c# - 等待多个后台线程

转载 作者:行者123 更新时间:2023-12-01 22:34:05 26 4
gpt4 key购买 nike

我想知道多线程程序中所有线程何时完成

没有像池这样的东西

while(!allThreadFinished){
thread.sleep(100);
}

该解决方案应该使用Monitor,但我不知道如何证明它是正确的。由于以下代码中的“SomeMethod”使用网络,因此会消耗时间。

public object SomeMethod(string input);
public object[] MultiThreadMethod(string[] inputs) {
var result = new object[inputs.Count()];
int i = 0;
foreach (var item in inputs) {
BackgroundWorker work = new BackgroundWorker();
work.DoWork += (sender, doWorkEventArgs) => { doWorkEventArgs.Result = SomeMethod(item); };
work.RunWorkerCompleted += (sender, runWorkerCompletedEventArgs) => {
result[i] = runWorkerCompletedEventArgs.Result;
};
i++;
work.RunWorkerAsync();
}
/////////////////////////////////////////////////////////////
//**wait while all thread has been completed**
/////////////////////////////////////////////////////////////
return result;
}

最佳答案

尝试使用 TPL http://msdn.microsoft.com/en-us/library/dd460717.aspx .

 List<Task> tasks = new List<Task>();

Task t1 = new Task(() =>
{
// Do something here...

});
t1.Start();
tasks.Add(t1);

Task t2 = new Task(() =>
{
// Do something here...

});
t2.Start();
tasks.Add(t2);

Task.WaitAll(tasks.ToArray());

关于c# - 等待多个后台线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12729505/

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