Making a function call on another thread using the C# Dispatcher class

There may be a situation when you need to execute a function on a different thread, such as ensuring that calls across the interface between a multi-threaded dll and its single-threaded user are made on the same, single thread. To achive this, you can use the target thread’s Dispatcher object as follows:

  1. Create a delegate of the function you wish to be able to call:
    public delegate void MyDelegate(int i, string str);
    public class TargetThreadClass
    {
        public TargetThreadClass()
        {
            MyDelegate del = new MyDelegate(this.FuncToExec);
        }
        public void FuncToExec(int i, string str)
        {
           // Do something
       }
    }
  2. Within the target thread, create an instance of a Dispatcher object and set it to the thread’s current dispatcher:
    Dispatcher UserDispatcher = Dispatcher.CurrentDispatcher;

    Then pass this dispatcher, along with the delegate into the source thread.

  3. Then to call FuncToExec on the target thread, use:
    UserDispatcher.Invoke(del, new object[] { 123, "arg string"});

    Where the first parameter of Invoke is the delegate itself and the second an array of the delegate’s parameters (if any), in this example the delegate takes an int and a string.

Tags: , , , ,

  1. #1 by Steve Godrich on January 22nd, 2010 - 1:49 pm

    Thank you for publishing this! The amount of time I’ve spent searching for a simple explanation like that is astonishing. You explain in both plain English and a simple implementation showing exactly how a delegate needs to be implemented. You’ve saved my sanity! :D

    RE Q
  2. #2 by richard on January 22nd, 2010 - 1:58 pm

    Hi Steve,

    No worries! I blog these little code snippets for exactly the same reason and I know I’ll end up needing one again eventually and won’t be able to remember how.

    I’m glad it helped!

    RE Q

SetPageWidth