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

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

    in Main:

    var m = new ManualResetEvent(false);
    // do something
    foreach (var url in urls)
    {
      Console.WriteLine("starting thread: " + url); 
      ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(myMethod), url);
    }
    m.WaitOne();
    
    
    private static void myMethod(object obj)
    {
      try{
       // do smt
      }
      finally {
        m.Set();
      }
    }
    

提交回复
热议问题