Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

winforms - C#: How to force "calling" a method from the main thread by signaling in some way from another thread

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 thread (is a C Library), I created the callback in C# and when gets called I would like to just raise an event.

However because I don't know what will be inside the event, I would like to find a way to invoke the method without the problem of locks and so on (otherwise the third party user will have to handle this inside the event, very ugly)

Are there any way to do this? I can be totally on the wrong way but I'm thinking about winforms way to handle different threads (the .Invoke thing)

Otherwise I can send a message to the message loop of the window, but I don't know a lot about message passing and if I can send "custom" messages like this

Example:

private uint lgLcdOnConfigureCB(int connection, System.IntPtr pContext)
{
    OnConfigure(EventArgs.Empty);
    return 0U;
}

this callback is called from another program which I don't have control over, I would like to run OnConfigure method in the main thread (the one that handles my winform), how to do it? Or in other words, I would like to run OnConfigure without the need of thinking about locks

Edit 1:

I have a problem with this exception:

CallbackOnCollectedDelegate retrived Message: Callback run on delegate 'G19dotNet!G19dotNet.LgLcd+lgLcdOnSoftButtonsCB::Invoke' collected in GarbageCollector. During unmanaged code delegates should be ensured will never be deleted until you are sure they will never be called

Edit 2:

Issue resolved by myself, thanks to Stackoverflow which always helps me! For future reference: Defining a delegate as a function pointer

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...