.NET 4.0 的 Task 类 - Promise 接口?

发布于 2024-12-28 15:03:07 字数 89 浏览 5 评论 0原文

Task 类是否有像 jQuery 的 deferred 的 promise 方法一样的 Promise 接口?

Is there a promise interface for the Task class like jQuery's deferred's promise method?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

萌无敌 2025-01-04 15:03:07

TPL 和Task 类与jQuery 的承诺有很大不同。

Task 实际上更像是原始操作。如果您希望在任务完成时运行某些内容,则可以在任务上使用延续。这实际上看起来更像是:

Task someTask = RunMethodAsync();
someTask.ContinueWith( t =>
{
   // This runs after the task completes, similar to how promise() would work
});

如果您想继续执行多个任务,可以使用 Task.Factory。ContinueWhenAllTask.Factory。ContinueWhenAny 到进行适用于多个任务的延续。

The TPL, and the Task class, are very different than jQuery's promise.

A Task is actually effectively more like the original action. If you wanted to have something run when the task completed, you'd use a continuation on the Task. This would effectively look more like:

Task someTask = RunMethodAsync();
someTask.ContinueWith( t =>
{
   // This runs after the task completes, similar to how promise() would work
});

If you want to continue on multiple tasks, you can use Task.Factory.ContinueWhenAll or Task.Factory.ContinueWhenAny to make continuations that works on multiple tasks.

野味少女 2025-01-04 15:03:07

看来您正在寻找 TaskCompletionSource:

var tcs = new TaskCompletionSource<Args>(); 

var obj = new SomeApi();

// will get raised, when the work is done
obj.Done += (args) => 
{
    // this will notify the caller 
    // of the SomeApiWrapper that 
    // the task just completed
    tcs.SetResult(args);
}

// start the work
obj.Do();

return tcs.Task;

代码取自此处: 何时应该使用 TaskCompletionSource< ;T>会被使用吗?

It seems like you're looking for TaskCompletionSource:

var tcs = new TaskCompletionSource<Args>(); 

var obj = new SomeApi();

// will get raised, when the work is done
obj.Done += (args) => 
{
    // this will notify the caller 
    // of the SomeApiWrapper that 
    // the task just completed
    tcs.SetResult(args);
}

// start the work
obj.Do();

return tcs.Task;

The code is taken from here: When should TaskCompletionSource<T> be used?

你对谁都笑 2025-01-04 15:03:07

这听起来像是一个延续,所以使用 .ContinueWith(callback);或者在 C# 5.0 中,只需 await,即

var task = /*...*/
var result = await task;
// everything here happens later on, when it is completed
// (assuming it isn't already)

不同的 API,但我认为它可以满足您的要求(有点难以确定......我不是< em>完全确信我理解这个问题)

That sounds like a continuation, so use .ContinueWith(callback); or in C# 5.0, simply await, i.e.

var task = /*...*/
var result = await task;
// everything here happens later on, when it is completed
// (assuming it isn't already)

different API, but I think it does what you are asking (a little hard to be sure... I'm not entirely sure I understand the question)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文