Marshalling Events Across Threads

前端 未结 2 1074
无人共我
无人共我 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.

提交回复
热议问题