【发布时间】:2016-08-19 04:10:58
【问题描述】:
我很难理解扩展方法。它们是静态类中的静态方法。它们是如何在内部初始化的?例如,我写了下面的扩展方法。它是线程安全的吗?
public static async Task TimeoutAfter(this Task task, TimeSpan timeSpan)
{
var cts = new CancellationTokenSource();
try
{
if (task.IsCompleted || timeSpan == Timeout.InfiniteTimeSpan)
return;
if (timeSpan == TimeSpan.Zero)
throw new TimeoutException();
if (task == await Task.WhenAny(task, Task.Delay(timeSpan, cts.Token)))
{
cts.Cancel();
await task;
}
else
{
throw new TimeoutException();
}
}
finally
{
cts.Dispose();
}
}
【问题讨论】:
-
“内部初始化”是什么意思?方法不是“初始化”的东西。
标签: c# .net thread-safety task-parallel-library extension-methods