C#  •  Marshal Calls to the Right Thread

Listing A. The Calculator class's Add() method adds two numbers. If the client were to call the Add() method directly, it would execute on the client's thread. Instead, the client uses ISynchronizeInvoke.Invoke() to marshal the call to the correct thread.

public class Calculator : ISynchronizeInvoke
{
   public int Add(int arg1,int arg2)
   {
      int threadID = 
         Thread.CurrentThread.GetHashCode();
      Trace.WriteLine(
         "Calculator thread ID is " + 
         threadID.ToString());
      return arg1 + arg2;
   }
   //ISynchronizeInvoke implementation 
   public object Invoke(Delegate method,object[] 
      args)
   {…}
   public IAsyncResult BeginInvoke(Delegate 
      method,object[] args)
   {…}
   public object EndInvoke(IAsyncResult result)
   {…}
   public bool InvokeRequired
   {…}
}
}
//Client-side code
public delegate int AddDelegate(int arg1,int 
   arg2);

int threadID = Thread.CurrentThread.GetHashCode();
Trace.WriteLine("Client thread ID is " + 
   threadID.ToString());

Calculator calc;
/* Some code to initialize calc */

AddDelegate addDelegate = new 
   AddDelegate(calc.Add);

object[] arr = new object[2];
arr[0] = 3;
arr[1] = 4;

int sum = 0;
sum = (int) calc.Invoke(addDelegate,arr);
Debug.Assert(sum ==7);

/*  Possible output:
Calculator thread ID is 29
Client thread ID is 30 
*/