BossRoss
BossRoss

Reputation: 869

convert starting dedicated threads to threadpool

What would be the equivalent way, using ThreadPool, to achieve the code below:

Receiver is a class that I am instantiating

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();                                                                                           
}

Upvotes: 0

Views: 173

Answers (3)

BossRoss
BossRoss

Reputation: 869

To answer my original question:

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

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


}

Upvotes: 0

Bassam Alugili
Bassam Alugili

Reputation: 17003

  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();
       }
    }
 }

Upvotes: 0

Bob Vale
Bob Vale

Reputation: 18474

Well you won't necessarily be able to name the threads if you switch to a ThreadPool, however you can just use the Task Parallel library to achieve your goals. TPL

One way would be

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

Or even using Parallel.ForEach

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

Upvotes: 3

Related Questions