non block event

donato

New member
Joined
Jun 23, 2020
Messages
1
Programming Experience
10+
Hi,

I'm using an event to execute a method "c_ThresholdReached" if I press a button, code example:
C#:
public event EventHandler ThresholdReached;

protected virtual void OnThresholdReached(EventArgs e)
{
    EventHandler handler = ThresholdReached;
    if (handler != null)
    {
        handler.Invoke(this, e);
    }
}

static void c_ThresholdReached(object sender, EventArgs e)
{
    Console.WriteLine("The threshold was reached.");
}

private void button_Click(object sender, EventArgs e)
{
    ThresholdReached += c_ThresholdReached;

    System.Console.WriteLine("in OnThresholdReached");
    OnThresholdReached(EventArgs.Empty);
    System.Console.WriteLine("out OnThresholdReached");
}
the output on console system is:
in OnThresholdReached
The threshold was reached.
out OnThresholdReached

the question is: if is it possible to complete the execution of method " button_Click " and subsequently is executed the method "c_ThresholdReached" raised from the event?
 
Last edited by a moderator:
Yes if OnThresholdareached() is called from another thread (e.g. a Task launched from a thread pool thread, a background worker thread, or an explicitly created thread). Otherwise, everything happens sequentially within a single thread -- there is no time travelling within a single thread even if you had a flux capacitor.
 
As an aside, I hope that you realize that a new event handler is registered on line 19 each time the button is clicked.
 
The question that you are asking in your text, is not quite what you were asking in your title, though. As I stated in my first reply, you could use a Task running in a thread pool thread. Another approach is to use a Task within the same thread, and take advantage of async/await. But the Task that you call needs to actually do something asynchronously, otherwise all the work will be done synchronously within the same call.

Tasks don't automatically fire of new threads. To fire off a new thread, you'll need Task.Run().
 
Back
Top Bottom