我正在开发一个 DelayedExecutor 类,它将延迟执行传递给其 DelayExecute 方法的 Action 特定时间 timeout(参见下面的代码)使用 async 和 await 语句。如果需要,我还希望能够在 timeout 间隔内中止执行。我写了一个小测试来测试它的行为,如下所示:
测试方法的代码:
[TestMethod]
public async Task DelayExecuteTest()
{
int timeout = 1000;
var delayExecutor = new DelayedExecutor(timeout);
Action func = new Action(() => Debug.WriteLine("Ran function!"));
var sw = Stopwatch.StartNew();
Debug.WriteLine("sw.ElapsedMilliseconds 1: " + sw.ElapsedMilliseconds);
Task delayTask = delayExecutor.DelayExecute(func);
await delayTask;
Debug.WriteLine("sw.ElapsedMilliseconds 2: " + sw.ElapsedMilliseconds);
Thread.Sleep(1000);
}
}
我期望从这个测试中得到的输出是它会告诉我:
sw.ElapsedMilliseconds outside DelayExecute 1: ...
Ran Action!"
sw.ElapsedMilliseconds inside DelayExecute: ...
sw.ElapsedMilliseconds outside DelayExecute 2:
但是我明白了,但不明白为什么:
sw.ElapsedMilliseconds outside DelayExecute 1: 0
sw.ElapsedMilliseconds outside DelayExecute 2: 30
Ran Action!
sw.ElapsedMilliseconds inside DelayExecute: 1015
在此blog post我阅读:
I like to think of “await” as an “asynchronous wait”. That is to say, the async method pauses until the awaitable is complete (so it waits), but the actual thread is not blocked (so it’s asynchronous).
这似乎符合我的预期,那么这是怎么回事,我的错误在哪里?
DelayedExecutor的代码:
public class DelayedExecutor
{
private int timeout;
private Task currentTask;
private CancellationToken cancellationToken;
private CancellationTokenSource tokenSource;
public DelayedExecutor(int timeout)
{
this.timeout = timeout;
tokenSource = new CancellationTokenSource();
}
public void AbortCurrentTask()
{
if (currentTask != null)
{
if (!currentTask.IsCompleted)
{
tokenSource.Cancel();
}
}
}
public Task DelayExecute(Action func)
{
AbortCurrentTask();
tokenSource = new CancellationTokenSource();
cancellationToken = tokenSource.Token;
return currentTask = Task.Factory.StartNew(async () =>
{
var sw = Stopwatch.StartNew();
await Task.Delay(timeout, cancellationToken);
func();
Debug.WriteLine("sw.ElapsedMilliseconds inside DelayExecute: " + sw.ElapsedMilliseconds);
});
}
}
更新:
按照建议,我在 DelayExecute
return currentTask = Task.Factory.StartNew(async () =>
进入
return currentTask = await Task.Factory.StartNew(async () =>
为了让它工作,我需要把签名改成这个
public async Task<Task> DelayExecute(Action func)
所以我的新定义是这样的:
public async Task<Task> DelayExecute(Action func)
{
AbortCurrentTask();
tokenSource = new CancellationTokenSource();
cancellationToken = tokenSource.Token;
return currentTask = await Task.Factory.StartNew(async () =>
{
var sw = Stopwatch.StartNew();
await Task.Delay(timeout, cancellationToken);
func();
Debug.WriteLine("sw.ElapsedMilliseconds inside DelayExecute: " + sw.ElapsedMilliseconds);
});
}
但是现在我的行为和以前一样了。有什么方法可以使用我的设计来实现我想要做的事情。还是它存在根本性缺陷?
顺便说一句,我也尝试将 await await delayTask; 放在我的测试 DelayExecuteTest 中,但这给了我错误
Cannot await 'void'
这是更新的测试方法 DelayExecuteTest,不编译:
public async Task DelayExecuteTest()
{
int timeout = 1000;
var delayExecutor = new DelayedExecutor(timeout);
Action func = new Action(() => Debug.WriteLine("Ran Action!"));
var sw = Stopwatch.StartNew();
Debug.WriteLine("sw.ElapsedMilliseconds outside DelayExecute 1: " + sw.ElapsedMilliseconds);
Task delayTask = delayExecutor.DelayExecute(func);
await await delayTask;
Debug.WriteLine("sw.ElapsedMilliseconds outside DelayExecute 2: " + sw.ElapsedMilliseconds);
Thread.Sleep(1000);
}
请您参考如下方法:
这里发生了一些事情,所以我将首先发布一个简单的答案,让我们看看它是否足够。
您已将任务包装在任务中,这需要双重等待。否则你只是在等待内部任务到达它的第一个返回点,这将(可以)在第一个 await。 .
让我们看看你的DelayExecute方法更详细。让我从更改方法的返回类型开始,我们将看到这如何改变我们的观点。返回类型的更改只是一个说明。您返回的是 Task现在是非通用的,实际上你返回的是 Task<Task> .
public Task<Task> DelayExecute(Action func)
{
AbortCurrentTask();
tokenSource = new CancellationTokenSource();
cancellationToken = tokenSource.Token;
return currentTask = Task.Factory.StartNew(async () =>
{
var sw = Stopwatch.StartNew();
await Task.Delay(timeout, cancellationToken);
func();
Debug.WriteLine("sw.ElapsedMilliseconds inside DelayExecute: " + sw.ElapsedMilliseconds);
});
}
(请注意,这不会编译,因为 currentTask 也是 Task 类型,但如果您阅读问题的其余部分,这在很大程度上是无关紧要的)
好的,那么这里发生了什么?
让我们先解释一个更简单的例子,我在LINQPad中测试过这个:
async Task Main()
{
Console.WriteLine("before await startnew");
await Task.Factory.StartNew(async () =>
{
Console.WriteLine("before await delay");
await Task.Delay(500);
Console.WriteLine("after await delay");
});
Console.WriteLine("after await startnew");
}
执行此操作时,我得到以下输出:
before await startnew
before await delay
after await startnew
after await delay -- this comes roughly half a second after previous line
为什么会这样?
嗯,你的StartNew返回 Task<Task> .这不是一个现在将等待内部任务完成的任务,它等待内部任务返回,它将(可以)在它的第一个await做。 .
所以让我们通过对有趣的行进行编号然后解释事情发生的顺序来查看完整的执行路径:
async Task Main()
{
Console.WriteLine("before await startnew"); 1
await Task.Factory.StartNew(async () => 2
{
Console.WriteLine("before await delay"); 3
await Task.Delay(500); 4
Console.WriteLine("after await delay"); 5
});
Console.WriteLine("after await startnew"); 6
}
1。第一个Console.WriteLine执行
这里没有什么神奇的
2。我们用 Task.Factory.StartNew 启动了一个新任务并等待它。
这里我们的 main 方法现在可以返回,它将返回一个任务,一旦内部任务完成,该任务将继续。
内部任务的工作不是执行该委托(delegate)中的所有代码。内部任务的工作是产生另一个任务。
这很重要!
3。内部任务现在开始执行
它基本上会执行委托(delegate)中的所有代码,包括对 Task.Delay 的调用。 ,它返回一个 Task .
4。内部任务到达它的第一个 await
因为这还没有完成(它只会在大约 500 毫秒后完成),这个委托(delegate)现在返回。
基本上,await <this task we got from Task.Delay>语句将创建一个延续,然后返回。
这很重要!
6。我们的外部任务现在继续
由于内部任务返回,外部任务现在可以继续。调用结果await Task.Factory.StartNew是另一项任务,但这个任务只能自生自灭。
5。内部任务,大约 500 毫秒后继续
现在是在外部任务已经继续执行之后,可能已完成执行。
因此总而言之,您的代码“按预期”执行,只是不是您预期的方式。
有几种方法可以修复此代码,我只是要重写您的 DelayExecute方法到最简单的方法来做你想做的事:
改变这一行:
return currentTask = Task.Factory.StartNew(async () =>
进入这个:
return currentTask = await Task.Factory.StartNew(async () =>
这将使内部任务启动您的秒表并到达第一个等待,然后一路返回DelayExecute。 .
与我上面的 LINQPad 示例类似的修复方法是简单地更改此行:
await Task.Factory.StartNew(async () =>
对此:
await await Task.Factory.StartNew(async () =>
