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

后端 未结 6 1230
感动是毒
感动是毒 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-09 00:02

    Simplest hack to fix your problem.

    In your program class:

    static volatile int ThreadsComplete = 0;
    

    In your "myMethod" at the end before return:

    //ThreadsComplete++; //*edit* for safety's sake
    Interlocked.Increment(ref ThreadsComplete);
    

    In your main method before it returns/ends:

    while(ThreadsComplete < urls.Count) { Thread.Sleep(10); }
    

    The above essentially hacks together a WaitForAll synchronization method.

提交回复
热议问题