"等待Task.Yield()"及其替代 [英] "await Task.Yield()" and its alternatives

查看:174
本文介绍了"等待Task.Yield()"及其替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我需要推迟code执行,直到UI线程的消息循环的未来迭代之后,我可以这样做是这样的:

If I need to postpone code execution until after a future iteration of the UI thread message loop, I could do so something like this:

await Task.Factory.StartNew(
    () => {
        MessageBox.Show("Hello!");
    },
    CancellationToken.None,
    TaskCreationOptions.None,
    TaskScheduler.FromCurrentSynchronizationContext());

这将类似于等待Task.Yield();的MessageBox.show(你好!); ,除了我有一个选项,取消任务,如果我想

This would be similar to await Task.Yield(); MessageBox.Show("Hello!");, besides I'd have an option to cancel the task if I wanted to.

在的情况下使用默认的同步情况下,我可以同样使用等待Task.Run 来继续在池中的线​​程。

In case with the default synchronization context, I could similarly use await Task.Run to continue on a pool thread.

其实,我很喜欢 Task.Factory.StartNew Task.Run 超过 Task.Yield ,因为它们都明确定义的范围,延续code。

In fact, I like Task.Factory.StartNew and Task.Run more than Task.Yield, because they both explicitly define the scope for the continuation code.

那么,在什么情况下等待Task.Yield()实际上是有用的?

So, in what situations await Task.Yield() is actually useful?

推荐答案

考虑这样的情况,当你想你的异步任务返回一个值。

Consider the case when you want your async task to return a value.

现有的同步方法:

public int DoSomething()
{
    return SomeMethodThatReturnsAnInt();
}

要进行异步,增加异步关键字和更改的返回类型:

To make async, add async keyword and change return type:

public async Task<int> DoSomething()

要使用Task.Factory.StartNew(),该方法的改变单线体为:

To use Task.Factory.StartNew(), change the one-line body of the method to:

// start new task
var task = Task<int>.Factory.StartNew(
    () => {
        return SomeMethodThatReturnsAnInt();
    },
    CancellationToken.None,
    TaskCreationOptions.None,
    TaskScheduler.FromCurrentSynchronizationContext() );

// await task, return control to calling method
await task;

// return task result
return task.Result;

VS。添加一行,如果你使用等待Task.Yield()

// this returns control to the calling method
await Task.Yield();

// otherwise synchronous method scheduled for async execution by the 
// TaskScheduler of the calling thread
return SomeMethodThatReturnsAnInt();

后者是更为简洁,易读,确实没有太大改变现有的方法。

The latter is far more concise, readable, and really doesn't change the existing method much.

这篇关于&QUOT;等待Task.Yield()&QUOT;及其替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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