gpt4 book ai didi

c# - 实现会改变 await 的行为吗?

转载 作者:太空宇宙 更新时间:2023-11-03 21:16:39 24 4
gpt4 key购买 nike

Await关键字与等待类型一起使用(.NET 带有现有的两种此类类型,TaskTask<T>)。但是,可以编写您自己的等待类型。

msdn blog post指出:

you can think of the following code:

await FooAsync();
RestOfMethod();

as being similar in nature to this:

var t = FooAsync();
var currentContext = SynchronizationContext.Current;
t.ContinueWith(delegate
{
if (currentContext == null)
RestOfMethod();
else
currentContext.Post(delegate { RestOfMethod(); }, null);
}, TaskScheduler.Current);

上面的(伪)代码是否遵循可等待类型的实现(例如 Task ),或者它只是编译器处理 any 可等待类型的方式右边await关键字?

在下面的评论部分,有一篇文章解释了 TaskScheduler 和 SynchronizationContext 之间的区别。

The primary difference is that SynchronizationContext is a general mechanism for working with delegates, whereas TaskScheduler is specific to and catered to Tasks (you can get a TaskScheduler that wraps a SynchronizationContext using TaskScheduler.FromCurrentSynchronizationContext). This is why awaiting Tasks takes both into account, first checking a SynchronizationContext (as the more general mechanism that most UI frameworks support), and then falling back to a TaskScheduler. Awaiting a different kind of object might choose to first use a SynchronizationContext, and then fall back to some other mechanism specific to that particular type.

如果我对最后一句话的理解正确,那就意味着我可以把我想要的任何代表放在 continueWith 中。方法(我指的是上面代码示例中的 t.ContinueWith 调用),即修改 await 的方式与我的自定义可等待对象一起使用时有效。

以防万一你想了解更多: http://blogs.msdn.com/b/pfxteam/archive/2009/09/22/9898090.aspx

最佳答案

Does the (pseudo)code above follow from the implementation of awaitable type (such as Task), or maybe is it just the way the compiler deals with any awaitable type that is on the right of the await keyword?

代码确实遵循具体任务的实现。但它的存在只是为了帮助您了解它是如何工作的,因为它与延续相似

编译器生成的实际代码大不相同,而且它没有考虑实际等待的类型。它所做的只是寻找一个 GetAwaiter 方法,该方法返回一个具有 IsCompletedGetResultOnCompleted 的等待程序。等待实现是捕获 SynchronizationContext.Current 或不捕获(或完全做其他事情)的实现。

可以看到实际代码here .

i.e. completely modify how await works when used with my custom awaitable object.

只要对您有意义,您就可以随心所欲。您甚至可以使用扩展方法使内置类型可等待。例如这段代码:

public static Awaiter GetAwaiter(this string s)
{
throw new NotImplementedException();
}
public abstract class Awaiter : INotifyCompletion
{
public abstract bool IsCompleted { get; }
public abstract void GetResult();
public abstract void OnCompleted(Action continuation);
}

将使您能够编译await "bar";。它当然会在运行时失败,但编译器不知道。

关于c# - 实现会改变 await 的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33764787/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com