What is the difference between task and thread in Managed Code?

 

Always that is an common question on using programming patterns and techniques.

A task is something you want doing.

A thread is one of possibly many workers who perform that task.

In .NET 4.0 terms, a Task represents an asynchronous operation. Thread(s) are used to complete that operation by breaking the work up into chunks and assigning to separate threads.

 

Using Asynchron  patterns in UI programming.

void async_uitasks()       
  {         
    // Nebenläufige Berechnung der Quadratwurzeln          
   Task.Factory.StartNew(() =>         
    {              
   double dSumme = 0.0;              
   for (int i = 0; i < 100000000; i++)               
  {                   
  dSumme += Math.Sqrt(i);               
  }               
  return dSumme;           
  }).ContinueWith(dTask =>       
      {                
 // Aufruf, wenn Berechnung beendet ist       
          sw.Stop();                
 // Sind wir im "richtigen" Thread?          
       if (textBoxResult.Dispatcher.CheckAccess())        
         {                
     // Ja, direkte Ausgabe der Ergebnisse                  
   UpdateUI(dTask.Result, sw.ElapsedMilliseconds, false);           
      }                 
else             
    {                    
 // Nein, Invoke benutzen            
         UpdateUIDelegate delUpdate = new UpdateUIDelegate(UpdateUI);                   
  textBoxResult.Dispatcher.Invoke(DispatcherPriority.Normal, delUpdate,          
             dTask.Result, sw.ElapsedMilliseconds, true);      
           }      
       });    
     }
 
NonBlocking tasks
 
   const int x = 3000;             const int y = 1000;          
   // Your scheduler            
 TaskScheduler scheduler = TaskScheduler.Default;           
  Task nonblockingTask = new Task(() =>          
   {                 
    CancellationTokenSource source = new CancellationTokenSource();               
  Task t1 = new Task(() =>               
  {                  
   while (true)       
     {                
         // Do something                      
    if (source.IsCancellationRequested)              
               break;                    
   }      
  }, source.Token);                
 t1.Start(scheduler);               
  // Wait for task 1             
    bool firstTimeout = t1.Wait(x);        
     if (!firstTimeout)                
    {              
     // If it hasn't finished at first timeout display message            
         Console.WriteLine("Message to user: the operation hasn't completed yet.");         
            bool secondTimeout = t1.Wait(y);    
                 if (!secondTimeout)             
        {               source.Cancel();      
                   Console.WriteLine("Operation stopped!");             
        }             
    }           
  });         
    nonblockingTask.Start();      
      Console.WriteLine("Do whatever you want...");            
 Console.ReadLine();        
Advertisements