在哪里定义基于任务的异步方法的回调 [英] Where to define callback for Task based asynchronous method

查看:37
本文介绍了在哪里定义基于任务的异步方法的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照这个问题,我正在尝试实现异步方法使用 TPL,并尝试遵循 TAP 指南.

Following this question, I am trying to implement an async method using the TPL, and trying to follow TAP guidelines.

我希望我的异步方法在完成后执行回调.据我所知,我可以通过三种方式做到这一点.

I want my async method to perform a callback when it's finished. As far as I can see there are three ways I can do this.

1) 在我的任务委托中手动回调

1) Callback manually in my task delegate

public Task DoWorkAsync(DoWorkCompletedCallback completedCallback)
{
    return Task.Factory.StartNew(
    { 
        //do work

        //call callback manually
        completedCallback();
    });
}

2) 为任务委托中的任务分配回调

2) Assign callback to task in task delegate

public Task DoWorkAsync(DoWorkCompletedCallback completedCallback)
{
    return Task.Factory.StartNew(
    { 
        //do work
    }
    ).ContinueWith(completedCallback); //assign callback to Task
}

3) 为调用者中的任务分配回调

3) Assign callback to task in caller

public Task DoWorkAsync()
{
    return Task.Factory.StartNew(
    { 
        //do work
    });
}

public void SomeClientCode()
{
    Task doingWork = DoWorkAsync();
    doingWork.ContinueWith(OnWorkCompleted);
}

我的直觉是 3 更正确,因为它将回调与方法分离,并且意味着客户端代码可以以任何它认为合适的方式管理任务(使用回调、轮询等),这似乎是 Tasks都是关于.但是,如果 DoWorkAsync() 在客户端代码挂钩其回调之前完成其工作会发生什么?

My gut feeling is that 3 is more correct, because it decouples the callback from the method, and means that client code can manage the task any way it sees fit (using callbacks, polling etc), which seems to be what Tasks are all about. However, what happens if DoWorkAsync() completes its work before the client code hooks up its callback?

是否有一种普遍接受的方法来做到这一点,还是太新了?

Is there a generally accepted way to do this or is it all too new?

做 2) 比做 1) 有什么优势吗?

Is there any advantage of doing 2) over 1)?

推荐答案

普遍接受的方式是3.

TPL 的用户通常知道他们可以使用 ContinueWith 继续任务.1 和 2 提供相同的功能,但具有非标准接口;用户必须弄清楚委托参数的含义以及要传递的内容,例如如果他们不想继续——所有这一切,同时该方法仍然返回一个可以以标准方式继续的任务.

Users of TPL generally know that they can continue a Task with ContinueWith. 1 and 2 provide the same functionality, but with a non-standard interface; the user has to figure out what the delegate parameter means and what to pass e.g. if they don't want to continue -- all that while the method still returns a Task that can be continued in the standard way.

这篇关于在哪里定义基于任务的异步方法的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆