Not logged in - Login

Simple multi-thread example

This is a simple mechanism to implement the execution of various tasks in separate threads.

public void test()
{
  // create a List object that contains Task objects.
  List<System.Threading.Tasks.Task> workerTasks = new List<System.Threading.Tasks.Task>();

  // run Task1 in a new thread.
  System.Threading.Tasks.Task<object> returnTask1 = System.Threading.Tasks.Task.Run(() => this.Task1(5));
  // add the returned task object to our list.
  workerTasks.Add(returnTask1);

  // run Task2 in a new thread
  System.Threading.Tasks.Task<object> returnTask2 = System.Threading.Tasks.Task.Run(() => this.Task2("test string"));
  // add the returned task object to our list.
  workerTasks.Add(returnTask2);

  // run Task3 in a new thread
  System.Threading.Tasks.Task<object> returnTask3 = System.Threading.Tasks.Task.Run(() => this.Task3());
  // add the returned task object to our list.
  workerTasks.Add(returnTask3);

  // optional- wait for all the tasks to complete.
  System.Threading.Tasks.Task.WaitAll(workerTasks.ToArray());

  // Since we waited for the tasks to complete, we can now access the returned values from the tasks.
  // Use the 'Result' field on the Task object to get the return value.
  object obj1 = returnTask1.Result;
  object obj2 = returnTask2.Result;
  object obj3 = returnTask3.Result;

}

public object Task1(int x)
{
  object rv = null;

  // simulate some work
  System.Threading.Thread.Sleep(5000);

  return rv;
}

public object Task2(string s)
{
  object rv = null;

  // simulate some work
  System.Threading.Thread.Sleep(5000);

  return rv;
}

public object Task3()
{
  object rv = null;

  // simulate some work
  System.Threading.Thread.Sleep(5000);

  return rv;
}