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

后端 未结 6 1130
感动是毒
感动是毒 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条回答
  •  北海茫月
    2021-02-09 00:04

    If you're using .net 4 then:

    urls.AsParallel().ForAll(MyMethod);
    

    Prior to .net 4 then start individual threads, keep them in a list and call Join(). The fact the workers are not background would keep them alive after the main thread exited, but the Join() is more explicit.

            List workers = new List();
            foreach(var url in urls)
            {
                Thread t = new Thread(MyMethod) {IsBackground = false};
                workers.Add(t);
                t.Start(url);
            }
    
            foreach (var worker in workers)
            {
                worker.Join();
            }
    

提交回复
热议问题