C# multi-threaded console application - Console quits before threads complete

后端 未结 6 1152
感动是毒
感动是毒 2021-02-08 23:14

I have a c# console application that creates up to 5 threads.

The threads are executing fine, but the UI thread shuts down as it finishes its work.

Is there a

6条回答
  •  旧时难觅i
    2021-02-08 23:44

    If you are using .NET 4.0:

    var tasks = new List();
    
    foreach(var url in urls)
    {
        tasks.Add(Task.Factory.StartNew(myMethod, url));
    }
    
    // do other stuff...
    
    // On shutdown, give yourself X number of seconds to wait for them to complete...
    Task.WaitAll(tasks.ToArray(), TimeSpan.FromSeconds(30));
    

提交回复
热议问题