How to 'await' raising an EventHandler event
Events don't mesh perfectly with async
and await
, as you've discovered.
The way UIs handle async
events is different than what you're trying to do. The UI provides a SynchronizationContext
to its async
events, enabling them to resume on the UI thread. It does not ever "await" them.
Best Solution (IMO)
I think the best option is to build your own async
-friendly pub/sub system, using AsyncCountdownEvent
to know when all handlers have completed.
Lesser Solution #1
async void
methods do notify their SynchronizationContext
when they start and finish (by incrementing/decrementing the count of asynchronous operations). All UI SynchronizationContext
s ignore these notifications, but you could build a wrapper that tracks it and returns when the count is zero.
Here's an example, using AsyncContext
from my AsyncEx library:
SearchCommand = new RelayCommand(() => {
IsSearching = true;
if (SearchRequest != null)
{
AsyncContext.Run(() => SearchRequest(this, EventArgs.Empty));
}
IsSearching = false;
});
However, in this example the UI thread is not pumping messages while it's in Run
.
Lesser Solution #2
You could also make your own SynchronizationContext
based on a nested Dispatcher
frame that pops itself when the count of asynchronous operations reaches zero. However, you then introduce re-entrancy problems; DoEvents
was left out of WPF on purpose.
await and event handler
The syntax for asynchronous event handlers is :
Something.PropertyChanged += IsButtonVisible_PropertyChanged;
...
private async void IsButtonVisible_PropertyChanged(object sender,
PropertyChangedEventArgs e)
{
if (IsSomethingEnabled)
{
await SomeService.ExecuteAsync(...);
}
}
This allows awaiting asynchronous operations inside the event handler without blocking the UI thread. This can't be used to await for an event in some other method though.
Awaiting a single event
If you want some other code to await for an event to complete you need a TaskCompletionSource. This is explained in Tasks and the Event-based Asynchronous Pattern (EAP).
public Task<string> OnPropChangeAsync(Something x)
{
var options=TaskCreationOptions.RunContinuationsAsynchronously;
var tcs = new TaskCompletionSource<string>(options);
x.OnPropertyChanged += onChanged;
return tcs.Task;
void onChanged(object sender,PropertyChangedEventArgs e)
{
tcs.TrySetResult(e.PropertyName);
x.OnPropertyChanged -= onChanged;
}
}
....
async Task MyAsyncMethod()
{
var sth=new Something();
....
var propName=await OnPropertyChangeAsync(sth);
if (propName=="Enabled" && IsSomethingEnabled)
{
await SomeService.ExecuteAsync(...);
}
}
This differs from the example in two places:
- The event handler delegate gets unregistered after the event fires. Otherwise the delegate would remain in memory as long as
Something
did. TaskCreationOptions.RunContinuationsAsynchronously
ensures that any continuations will run on a separate thread. The default is to run them on the same thread that sets the result
This method will await only a single event. Calling it in a loop will create a new TCS each time, which is wasteful.
Awaiting a stream of events
It wasn't possible to easily await
multiple events until IAsyncEnumerable was introduced in C# 8. With IAsyncEnumerable<T>
and Channel, it's possible to create a method that will send a stream of notifications :
public IAsyncEnumerable<string> OnPropChangeAsync(Something x,CancellationToken token)
{
var channel=Channel.CreateUnbounded<string>();
//Finish on cancellation
token.Register(()=>channel.Writer.TryComplete());
x.OnPropertyChanged += onChanged;
return channel.Reader.ReadAllAsync();
async void onChanged(object sender,PropertyChangedEventArgs e)
{
channel.Writer.SendAsync(e.PropertyName);
}
}
....
async Task MyAsyncMethod(CancellationToken token)
{
var sth=new Something();
....
await foreach(var prop in OnPropertyChangeAsync(sth),token)
{
if (propName=="Enabled" && IsSomethingEnabled)
{
await SomeService.ExecuteAsync(...);
}
}
}
In this case, only one event handler is needed. Every time an event occurs the property named is pushed to the Channel
. Channel.Reader.ReadAllAsync()
is used to return an IAsyncEnumerable<string>
that can be used to loop asynchronously. The loop will keep running until the CancellationToken
is signaled, in which case the writer will go into the Completed
state and the IAsyncEnumerable<T>
will terminate.
How do I await events in C#?
Personally, I think that having async
event handlers may not be the best design choice, not the least of which reason being the very problem you're having. With synchronous handlers, it's trivial to know when they complete.
That said, if for some reason you must or at least are strongly compelled to stick with this design, you can do it in an await
-friendly way.
Your idea to register handlers and await
them is a good one. However, I would suggest sticking with the existing event paradigm, as that will keep the expressiveness of events in your code. The main thing is that you have to deviate from the standard EventHandler
-based delegate type, and use a delegate type that returns a Task
so that you can await
the handlers.
Here's a simple example illustrating what I mean:
class A
{
public event Func<object, EventArgs, Task> Shutdown;
public async Task OnShutdown()
{
Func<object, EventArgs, Task> handler = Shutdown;
if (handler == null)
{
return;
}
Delegate[] invocationList = handler.GetInvocationList();
Task[] handlerTasks = new Task[invocationList.Length];
for (int i = 0; i < invocationList.Length; i++)
{
handlerTasks[i] = ((Func<object, EventArgs, Task>)invocationList[i])(this, EventArgs.Empty);
}
await Task.WhenAll(handlerTasks);
}
}
The OnShutdown()
method, after doing the standard "get local copy of the event delegate instance", first invokes all of the handlers, and then awaits all of the returned Tasks
(having saved them to a local array as the handlers are invoked).
Here's a short console program illustrating the use:
class Program
{
static void Main(string[] args)
{
A a = new A();
a.Shutdown += Handler1;
a.Shutdown += Handler2;
a.Shutdown += Handler3;
a.OnShutdown().Wait();
}
static async Task Handler1(object sender, EventArgs e)
{
Console.WriteLine("Starting shutdown handler #1");
await Task.Delay(1000);
Console.WriteLine("Done with shutdown handler #1");
}
static async Task Handler2(object sender, EventArgs e)
{
Console.WriteLine("Starting shutdown handler #2");
await Task.Delay(5000);
Console.WriteLine("Done with shutdown handler #2");
}
static async Task Handler3(object sender, EventArgs e)
{
Console.WriteLine("Starting shutdown handler #3");
await Task.Delay(2000);
Console.WriteLine("Done with shutdown handler #3");
}
}
Having gone through this example, I now find myself wondering if there couldn't have been a way for C# to abstract this a bit. Maybe it would have been too complicated a change, but the current mix of the old-style void
-returning event handlers and the new async
/await
feature does seem a bit awkward. The above works (and works well, IMHO), but it would have been nice to have better CLR and/or language support for the scenario (i.e. be able to await a multicast delegate and have the C# compiler turn that into a call to WhenAll()
).
Event handler raised twice in async method
Check invocation list of the event:
EventHandler e = NotifyDataEvent;
var count = e.GetInvocationList().Length;
If count = 2
then you call NotifyDataEvent +=...
twice. If count = 1
then you call NotifyDataEvent.Invoke...
twice.
Is it possible to await an event instead of another async method?
You can use an instance of the SemaphoreSlim Class as a signal:
private SemaphoreSlim signal = new SemaphoreSlim(0, 1);
// set signal in event
signal.Release();
// wait for signal somewhere else
await signal.WaitAsync();
Alternatively, you can use an instance of the TaskCompletionSource<T> Class to create a Task<T> that represents the result of the button click:
private TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
// complete task in event
tcs.SetResult(true);
// wait for task somewhere else
await tcs.Task;
Await async with event handler
As a rule when you want to convert some non-task based asynchronous model to a task based asynchronous model, if there isn't already a Task
method to do the conversion for you, you use a TaskCompletionSource
to handle each of the cases "manually":
public Task<IApiData> FetchQueuedApiAsync(TimeSpan receiveTimeout)
{
var tcs = new TaskCompletionSource<IApiData>();
ReadQueue.BeginReceive(receiveTimeout);
ReadQueue.ReceiveCompleted += (sender, args) =>
{
if (timedOut)
tcs.TrySetCanceled();
else if (threwException)
tcs.TrySetException(exception);
else
tcs.TrySetResult(ReadQueue.EndReceive() as IApiData);
};
return tcs.Task;
}
You'll need to adjust this based on the specifics of the types you didn't show, but this is the general idea.
Moq Raise for an async event listener
You can convert the test to be async as well and await a delayed task to allow the async event handler to perform its functionality.
The following example uses a delay in the even handler to simulate a potential long running task.
public interface IService {
event EventHandler OnResultsChanged;
}
public class Provider {
private IService _service;
public Provider(IService service) {
_service = service;
_service.OnResultsChanged += ChangeResults;
}
private async void ChangeResults(object sender, EventArgs e) {
await Task.Delay(200); //<-- simulate delay
await Task.Run(() => HasResults = true);
}
public bool HasResults { get; set; }
}
By converting the test to async and waiting for the raised event, the assertion was able to be asserted.
[TestClass]
public class MyTestClass {
[TestMethod]
public async Task Test() {
//Arrange
var serviceMock = new Mock<IService>();
var systemUnderTest = new Provider(serviceMock.Object) {
HasResults = false
};
//Act
serviceMock.Raise(mock => mock.OnResultsChanged += null, EventArgs.Empty);
await Task.Delay(300); //<--wait
//Assert
Assert.IsTrue(systemUnderTest.HasResults);
}
}
How to make form events to use benefits from async?
I think bellow proposition is nice and functional. However it's break sometimes forms in the DevExpress Design mode. So I put my solution to futher discussion:
public Form1 : Form
{
public Form1()
{
...
this.button1.Click +=
new System.EventHandler(
async (sender, events) => await this.button1_Click(sender, events)
);
}
private async Task button1_Click(object sender, EventArgs e) // line A
{
}
}
Related Topics
Ilookup<Tkey, Tval> VS. Igrouping<Tkey, Tval>
How to Send an Email in .Net According to New Security Policies
Testinitialize VS Classinitialize
Issue with List.Add() Only Saving the Last Added Item
How Can a Wpf Usercontrol Inherit a Wpf Usercontrol
Creating Powerpoint Presentations Programmatically
Why Method Overloading Is Not Allowed in Wcf
An Expression Tree May Not Contain a Call or Invocation That Uses Optional Arguments
How to Make an Installer for My C# Application
Linq to Entities Does Not Recognize the Method 'System.Web.Mvc.Fileresult'
How to Reduce Memory Consumption of PDFptable with Many Cells
Creating a SQL Server Table from a C# Datatable
Control Another Application Using C#
Create Web Service Proxy in Visual Studio from a Wsdl File
Cannot Load Counter Name Data Because an Invalid Index -Exception