How to Raise an Event in C # - Best Approach

I am writing a Windows Form application. It has a thread to perform some operation, and when the operation finds something, it must notify the main form in order to change the control.

The notification currently uses the C # event usage described on the following MSDN page: http://msdn.microsoft.com/en-us/library/wkzf914z(VS.71).aspx

But I'm not sure about the delegate. Because in the situation described above, the thread calls the delegate. Is this a thread-safe approach for raising events?

Is it better to implement Windows messages (SendMessage) in C # and then implement a message handler in WindowProc.

Estimate time on it.

+3
source share
3 answers

If you don’t need very fine control over stream processing, you can use BackgroundWorker instead . It processes the entire data transmission on several channels. You basically put your background code in a DoWork event handler, and then pass the data back to the user interface stream through the ProgressChanged and RunWorkerCompleted events. The link above provides a complete example of how to use it.

, , . , , . , BackgroundWorker.

, . , , , , .

class MyClass {

    public event EventHandler SomethingHappened;

    protected virtual void OnSomethingHappened(EventArgs e) {
        EventHandler handler = SomethingHappened;
        if (handler != null) {
            handler(this, e);
        }
    }

    public void DoSomething() {
        OnSomethingHappened(EventArgs.Empty);
    }

}
+4

, , . , . , InvokeRequired .

void OnStatusMessage(string s)
{
  // might be coming from a different thread
  if (txtStatus.InvokeRequired)
  {
    this.BeginInvoke(new MethodInvoker(delegate()
    {
      OnStatusMessage(s);
    }));
  }
  else
  {
    StatusBox.Text += s + "\r\n";
    StatusBox.SelectionStart = txtStatus.TextLength;
    StatusBox.ScrollToCaret();
  }
}

BackgroundWorker, . , ThreadPool WaitCallBack (*) .

Windows , , , . ( , + = )

  • WaitCallBack, .
0
source

Source: https://habr.com/ru/post/1751136/


All Articles