Sorry for long title, I don\'t know even the way on how to express the question
I\'m using a library which run a callback from a different context from the main thre
If you're using WinForms and you want to execute something on the UI thread, you need to call either Invoke
or BeginInvoke
on some control (be it a Button
or a Form
or whatever) that was created on that thread. You'll need a reference to it in order to do this.
For example, with your code and assuming that you have a reference to a form called form
:
private uint lgLcdOnConfigureCB(int connection, System.IntPtr pContext)
{
form.Invoke(new MethodInvoker(() => OnConfigure(EventArgs.Empty)));
return 0U;
}
Before you call the 3rd party function, get a reference to Dispatcher.CurrentDispatcher. In the callback function, use dispatcher.Invoke.
What you end up with will look something like this:
class MyClass
{
private Dispatcher dispatcher;
public void runThirdParty()
{
this.dispatcher = Dispatcher.CurrentDispatcher;
callThirdPartyFunction(myCallBack);
}
public void myCallBack()
{
this.dispatcher.Invoke(new Action(() =>
{
//code to run here.
}));
}
}
There is a pattern for this called Event-based Asynchronous Pattern. The article linked is a great overview on how to use it. The AsyncOperation class is the key to this pattern.
This pattern might not fit perfectly with your problem that you are trying to solve, but it might give you some insights into the problem.