将启动专用线程转换为线程池

时间:2013-10-11 11:42:16

标签: c# multithreading

使用ThreadPool实现以下代码的等效方法是什么:

Receiver是我实例化的一个类

foreach (MobileAccounts MobileAccount in ReceiverAccounts)
{                        
    Receiver rec = new Receiver();
    ThreadStart starterParameters = delegate { rec.StartListener(MobileAccount); };
    Thread FeedbackThread = new Thread(starterParameters);
    FeedbackThread.Name = MobileAccount.FriendlyName;

    FeedbackThread.Start();                                                                                           
}

3 个答案:

答案 0 :(得分:3)

如果你切换到ThreadPool,你不一定能够命名线程,但是你可以使用任务并行库来实现你的目标。 TPL

一种方法是

foreach (MobileAccounts MobileAccount in ReceiverAccounts) {
  Receiver rec = new Receiver();
  Task.Run(() => rec.StartListener(MobileAccount));
}

甚至使用Parallel.ForEach

Parallel.ForEach(ReceiverAccounts, 
                 MobileAccount => new Receiver().StartListener(MobileAccount));

答案 1 :(得分:0)

  var tokenSource2 = new CancellationTokenSource();

  foreach (MobileAccounts MobileAccount in ReceiverAccounts)
  {
    var rec = new Receiver();
    var ct = tokenSource2.Token;
    Task.Factory.StartNew(() => this.DoWorkEventArgs(rec, ct));
  }

 // Anywhere outside you can call tokenSource2.Cancel();


 private void DoWorkEventArgs(Receiver rec, CancellationToken ct)
 {
   // Were we already canceled?
   ct.ThrowIfCancellationRequested();

   bool moreToDo = true;
   while (moreToDo)
   {
       // Poll on this property if you have to do 
       // other cleanup before throwing. 
       if (ct.IsCancellationRequested)
       {
         // Clean up here, then...
         ct.ThrowIfCancellationRequested();
       }
    }
 }

答案 2 :(得分:0)

回答我原来的问题:

foreach (MobileAccounts MobileAccount in ReceiverAccounts)
{
    Receiver rec = new Receiver();

    ThreadPool.QueueUserWorkItem(delegate { rec.StartListener(MobileAccount); }, null);                    


}