开发者

Using Cancellation with Async Tasks

Is there a way to cancel an Async System.Threading.Tasks.Task? i.e.

Task.Factory.FromAsync(
    client.BeginCallWebService, 
    client.EndCallWebService, 
    "param1", 
    null);

I would like to register a shared CancellationToken with this task so that if the token is cancelled before this Async task is invoked, it won't be invoked.

Than开发者_如何转开发ks


So, having put some more thought into this I think cancelling an Async task makes no sense as the Begin part will be invoked 'inline' that, is right away on the calling thread.

Therefore there is no need to support cancellation in this way.

If you wanted to actually abort a processing call (e.g. to a web service or using web client) you could implement a TaskCompletionSource approach instead as documented here: http://msdn.microsoft.com/en-us/library/ee622454.aspx

Sorry to answer my own question, I'm guessing that's a bit of no-no.


I would disagree to the notion that Cancelling an Async Task makes no sense.

You are correct, that it usually would by invoked right away (and a hot task is returned) but that is not always the case, for example when you use a TaskFactory which uses an OrderedTaskScheduler (a class executes one task after another). OrderedTaskScheduler is contained in http://archive.msdn.microsoft.com/ParExtSamples/Release/ProjectReleases.aspx?ReleaseId=4179

Take care, Martin

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜