Eri*_*ric 1 c# lambda task-parallel-library
在MSFT的基于任务的异步模式白皮书(第11页)中,Stephen Toub有以下代码说明围绕Timer回调包装任务.
public static Task<DateTimeOffset> Delay(int millisecondsTimeout)
{
var tcs = new TaskCompletionSource<DateTimeOffset>();
new Timer(self =>
{
((IDisposable)self).Dispose(); //<--this is the line in question
tcs.TrySetResult(DateTimeOffset.UtcNow);
}).Change(millisecondsTimeout, -1);
return tcs.Task;
}
Run Code Online (Sandbox Code Playgroud)
在第6行,他演员self为IDisposable.如果我正确地读取这个lambda表达式,那么self会"转到"一个没有实现的TimerCallbackIDisposable.我读错了吗?
参数self是在调用委托(lambda)时传递的参数Timer.根据MSDN,该代表的类型是TimerCallback:
public delegate void TimerCallback(Object state)
Run Code Online (Sandbox Code Playgroud)
当你没有在Timer构造函数中给出状态时,它使用Timer实例本身作为状态:
如果要将Timer对象本身用作状态对象,请调用此构造函数.
所以自己将成为Timer的实例,可以安全地作为IDisposable进行转换.虽然参数的类型object意味着它必须是子类,object其中.NET可以是任何类型.
| 归档时间: |
|
| 查看次数: |
165 次 |
| 最近记录: |