Use Thread Task to run method - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Task

Description

Use Thread Task to run method

Demo Code

using System;//  w w w  .  j  ava 2s  .  c  o  m
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using static System.Console;
class Program
{
   static Random r = new Random();
   static string Message; // a shared resource
   static object conch = new object();
   static void MethodA()
   {
      lock (conch)
      {
         for (int i = 0; i < 5; i++)
         {
            Thread.Sleep(r.Next(2000));
            Message += "A";
            Write(".");
         }
      }
   }
   static void MethodB()
   {
      lock (conch)
      {
         for (int i = 0; i < 5; i++)
         {
            Thread.Sleep(r.Next(2000));
            Message += "B";
            Write(".");
         }
      }
   }
   static void Main(string[] args)
   {
      Stopwatch watch = Stopwatch.StartNew();
      Task a = Task.Factory.StartNew(MethodA);
      Task b = Task.Factory.StartNew(MethodB);
      Task.WaitAll(new Task[] { a, b });
      WriteLine($"Results: {Message}.");
      WriteLine($"{watch.ElapsedMilliseconds:#,##0} elapsed milliseconds.");
   }
}

Result


Related Tutorials