Marshalling Events Across Threads

前端 未结 2 1075
无人共我
无人共我 2021-01-25 03:29

I imagine this may be marked as repetitious and closed, but I cannot for the life of me find a clear, concise answer to this question. All the replies and resources deal almost

相关标签:
2条回答
  • 2021-01-25 04:18

    You cannot magically execute code on an existing thread.
    Instead, you need the existing thread to explicitly execute your code, using a thread-safe data structure to tell it what to do.

    This is how Control.Invoke works (which is in turn how BackgroundWorker works).
    WiinForms runs a message loop in Application.Run() which looks roughly like this:

    while(true) {
        var message = GetMessage();  //Windows API call
        ProcessMessage(message);
    }
    

    Control.Invoke() sends a Windows message (using thread-safe message passing code within Windows) telling it to run your delegate. ProcessMessage (which executes on the UI thread) will catch that message and execute the delegate.

    If you want to do this yourself, you will need to write your own loop. You can use the new thread-safe Producer-Consumer collections in .Net 4.0 for this, or you can use a delegate field (with Interlocked.CompareExchange) and an AutoResetEvent and do it yourself.

    0 讨论(0)
  • 2021-01-25 04:22

    Note: im writing this here because theres not enough space on comments, this is of course not a complete, nor half a complete answer:

    I've always used Events to signal unrelated code to do something, so that was how I described my intent. Forgive me though, I'm not sure I see the difference between marshaling and event versus marshaling another type of data (signal).

    Conceptually both can be treated as events. The difference between using provided sync/signalining objects and trying to implement something like this by urself, is who and how gets the job done.

    An event in .net is just a delegate, a list of pointers to methods that should be executed when the provider of the event fires it. What youre talking about (marshalling the event), if i understand you correctly, is sharing the event object when something happens, while the concept of signalig usually talks about an object which is shared to start with, and both threads "know" something happened by checking its state either manualy or automatily (relying on provided tools by both .net and windows).

    In the most basic scenario, you can implement such a signaling concept by using a boolean variable, with one thread constantly looping to check if the value of the boolean is true, and another setting to such, as a way to signal something happend. The different signaling tools provided by .NET do this in a less resource-wasting maner, by also not executing the waiting thread, as long as theres no signal (the boolean equals to false), but conceptually, it is the same idea.

    0 讨论(0)
提交回复
热议问题