gpt4 book ai didi

c# - 为什么 Task 实现了 IAsyncResult,但不包含 AsyncWaitHandle 成员?

转载 作者:太空狗 更新时间:2023-10-29 22:37:25 26 4
gpt4 key购买 nike

也许这是个愚蠢的问题。

Task 类是这样声明的:

public class Task : IThreadPoolWorkItem, IAsyncResult, IDisposable

IAsyncResult 接口(interface)声明如下:

public interface IAsyncResult
{
object AsyncState { get; }
WaitHandle AsyncWaitHandle { get; }
bool CompletedSynchronously { get; }
bool IsCompleted { get; }
}

但是成员AsyncWaitHandle不存在于Task类或实例中。

这段代码:

System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(() => { }); 
t.AsyncWaitHandle.ToString();

引发此编译错误:

Error 1 'System.Threading.Tasks.Task' does not contain a definition for 'AsyncWaitHandle' and no extension method 'AsyncWaitHandle' accepting a first argument of type 'System.Threading.Tasks.Task' could be found (are you missing a using directive or an assembly reference?)

然而,这不仅编译:

System.IAsyncResult t = new System.Threading.Tasks.Task(() => { }); 
t.AsyncWaitHandle.ToString();

但也有效,因为该成员存在。这是什么魔法?

这是编译器的把戏还是以其他方式隐藏了?

干杯。

最佳答案

Task 显式实现了 IAsyncResult,因此您必须先进行转换:

System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(() => { }); 
((IAsyncResult)t).AsyncWaitHandle.ToString()

显式实现定义如下:

public class Task : IAsyncResult
{
WaitHandle IAsyncResult.AsyncWaitHandle
{
get { ... }
}
}

关于c# - 为什么 Task 实现了 IAsyncResult,但不包含 AsyncWaitHandle 成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22174209/

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