How to send a notification to another thread/process in C#?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aircw
    New Member
    • Oct 2008
    • 1

    How to send a notification to another thread/process in C#?

    My question has such a scenario:
    Two threads, thread1(e.g. UI thread in WPF) and thread2,

    thread1 starts thread2 in threadpool and returns to handle other UI events. What thread2 does is to start a process until complete, then notify thread1 it is done, returns an exitcode to thread1.
    The problem is how to make thread1 do other things while thread2 is busy with some computation, but responds immediately when the process in thread2 returns.

    public class Window1:Window
    {
    onbuttonrunclic k()
    {
    start thread2
    }
    .....
    }

    thread2
    {
    create WorkProcess.
    WorkProcess.sta rt();
    WorkProcess.wai tforexit();
    }

    Even further, is it possible get rid of thread2, and use some inter-process communication mechanism to notify UI the exitcode of the WorkProcess.

    Any suggestion is greatly appreciated.
  • mldisibio
    Recognized Expert New Member
    • Sep 2008
    • 191

    #2
    If Thread1 is truly a GUI/Windows Form, then the safest and easiest way to accomplish what you want is using the BackgroundWorke r Class .

    Also, please consult a very authoritative and freely available overview of threading and synchronization : Threading in C# by Joseph Albahari. He has an extensive example of using the BackgoundWorker .

    A Framework GUI is single threaded. That is, any updates or communication to the GUI thread can only be done on that thread. If your second thread attempts to update the GUI without being marshalled back to the original GUI thread, ThreadException s will occur.

    There are ways to accomplish this with thread callbacks, delegates and the use of Form.InvokeRequ ired and Form.Invoke. Happily however, the BackgroundWorke r does all this work for you. As long as the BackgroundWorke r is created by the GUI, then its callback (RunWorkerCompl eted) will also be marshalled back to the GUI thread.

    Comment

    Working...