简体   繁体   中英

Async / Await using delegates

I want to subscribe an async method to an event.

However, the compiler will not let me.

How can I do this?

Example:

class SearchBase
{
    public delegate void ReuestingCollectionHandler();
    public event ReuestingCollectionHandler RequestingCollection = null;
}
.
.
.
SearchBase.RequestingCollection += LoadCandidates;


 public async Task LoadCandidates()
 {
    var queryText = string.Empty;
    Candidates = await CandidatesManager.GetCandidates(Profile.Instance.RecruiterId);
 }

Is your LoadCandidates method going to be used only as an event handler (like the code you posted shows)?

If so, you should change it to be async void instead of returning a Task . That's the usual signature for event handlers, and one of the very few cases where having an async void method is acceptable/recommended.

If you're gonna use it somewhere else and need it to return a task, then write an async void wrapper method around it, and use this wrapper as the event handler instead.

public async void LoadCandidatesAsync()
 {
    await LoadCandidates();
 }

Event handlers should NOT return anything. If a caller has 100 clients listening to that event, he will only get the return value of one of the handlers. If the caller wants to get something out of the handlers, then it should send them a mutable EventArgs instance.

Here's a more complete explanation on why event handlers should return void : https://stackoverflow.com/a/3325425/857807

您的委托需要匹配,您无法分配将Task返回到返回类型为void的委托的方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM