I have numerous functions that are called from a background thread, but then need to perform a GUI operation. Therefore in each function, I switch context to the GUI thread. However I’m wondering if my code can be improved?
Here’s a cut down example of how my code typically looks now:
public void FunctionABC(string test)
{
// Make sure we are in the GUI thread.
if (!this.Dispatcher.CheckAccess())
{
this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => FunctionABC(test))); return;
}
// main body of function
}
The main part I have a problem with is having to mention my own function name explicitly in the context switch (I partly dislike this because I keep forgetting to change the name when I copy and paste the code!)
Any ideas for a more generic way of switching context, e.g. is any way of calling back into my own function via some clever pointer that avoids naming the function explicitly?
Something like this snippet would be good (which doesn’t build however):
this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => this(test))); return;
Thoughts?
How about pulling the dispatch code into a separate method?
and: