gpt4 book ai didi

c# - Foreach thread.join,没有按预期工作,如何解决?

转载 作者:太空宇宙 更新时间:2023-11-03 14:42:49 25 4
gpt4 key购买 nike

我想在几个线程中运行一些方法,这个方法需要一些参数。当我尝试执行它时,我的测试没有通过,因为一些线程无法结束。但是,在函数结束时我使用 Foreach { thread.join } 这是我的代码:(路径 - 一些对象的列表。解析 - 带有来自路径的对象的方法。)

public void RunAsync()
{
Thread[] threadArr = new Thread[Paths.Count];
var pathsArr = Paths.ToArray();

for (int i = 0; i < PathsArr.Length; i++)
{
threadArr[i] = new Thread(new ParameterizedThreadStart(Parse));
threadArr[i].Start((PathsArr[i]));
}

foreach (var thread in threadArr)
{
thread.Join();
}
}

在这种情况下,我该如何修复它或需要使用哪些构造/技术?我想在几个线程中执行此操作,因为同步执行此操作时间太长。

最佳答案

Thread.Join() 将阻止您当前的线程。这意味着每个 foreach 循环都将在最后一次运行后执行。

我想你想要Start()你的线程来并行执行它们。

这里有一个例子:

// Example-Work-Method
public static void MyAction(int waitSecs)
{
Console.WriteLine("Starting MyAction " + waitSecs);
Thread.Sleep(waitSecs * 1000);
Console.WriteLine("End MyAction " + waitSecs);
}

public static void Main(string[] args)
{
// We create a bunch of actions which we want to executte parallel
Action[] actions = new Action[]
{
new Action(() => MyAction(1)),
new Action(() => MyAction(2)),
new Action(() => MyAction(3)),
new Action(() => MyAction(4)),
new Action(() => MyAction(5)),
new Action(() => MyAction(6)),
new Action(() => MyAction(7)),
new Action(() => MyAction(8)),
new Action(() => MyAction(9)),
new Action(() => MyAction(10)),
};

// create a thread for each action
Thread[] threads = actions.Select(s => new Thread(() => s.Invoke())).ToArray();

// Start all threads
foreach (Thread t in threads)
{
t.Start();
}
// This will "instantly" outputted after start. It won't if we'd use Join()
Console.WriteLine("All threads are running..");

// And now let's wait for the work to be done.
while (threads.Any(t => t.ThreadState != ThreadState.Stopped))
Thread.Sleep(100);

Console.WriteLine("Done..");
}

您可能应该问问自己是否要调用此方法 Async。 c# 中的异步方法带来了一些其他机制。看看这个:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/async

关于c# - Foreach thread.join,没有按预期工作,如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56035745/

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