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:
- 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 } }
- 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.
- 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.