Foreach thread.join,不能按预期工作,如何解决?

时间:2019-05-08 07:37:07

标签: c# asynchronous

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

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();
    }
}

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

1 个答案:

答案 0 :(得分:0)

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://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/async