Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

c# - 是否有一种内置方法让异步方法在完成时使用返回数据来触发事件?(Is there a built-in way to have an async method fire an event with the return data when it completes?)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Maybe you are searching for the ContinueWith method?

(也许您正在搜索ContinueWith方法?)

The caller can create an "event" by chaining a continuation to the task:

(调用者可以通过将延续链接到任务来创建“事件”:)

Task<string> task = MyAsyncMethod();
task.ContinueWith(_ => { /* Event handler */ });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...