Let's say I've created a library with the following async method:
(假设我使用以下异步方法创建了一个库:)
public async Task<string> MyAsyncMethod()
{
// Do stuff
return someString;
}
Now let's say I want the app developer to be able to call this method in a typical fire-and-forget fashion, but then consume an event with the return data when the method completes.
(现在让我们说我希望应用程序开发人员能够以一种典型的“一劳永逸”的方式调用此方法,但是在该方法完成时使用带有返回数据的事件。)
If I were to do this manually, it might look something like this:
(如果我要手动执行此操作,则可能如下所示:)
public async Task<string> MyAsyncMethod()
{
// Do stuff
// Fire the success event
MyEvent?.Invoke(this, new MyEventArgs { Result = someString });
return someString;
}
...
// Use this callback method to consume the event
public void C_MyAsyncMethodHasCompleted(object sender, MyEventArgs e)
{
Console.WriteLine("Async method has completed with return value: " + e.Result);
}
Here's my question: Is it a waste of time to do it like this?
(这是我的问题:这样做是否浪费时间?)
Ie is there some simpler, built-in thing with C# and/or .NET that already does this? (即使用C#和/或.NET有一些更简单的内置东西已经做到了吗?)
I mainly just want to make sure I'm not reinventing the wheel with this approach.
(我主要只是想确保我不会使用这种方法来重新发明轮子。)
ask by Kris Craig translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…