Skip to content


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.

Did you like this? Share it:

Posted in C#, Software Development.

Tagged with , , , , .


2 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Steve Godrich says

    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

  2. richard says

    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!



Some HTML is OK

or, reply to this post via trackback.