我正在尝试创建一个简单的可重用超时方法,它是完全异步的。出于某种原因,我的 Timeout 方法没有被等待,我不知道为什么。 [Fact] public async void TestTimeOut() { Stopwatch sw = Stopwatch.StartNew(); var Thrown = false; try { await TimeOut(() => Task.Delay(5000), TimeSpan.FromMilliseconds(1000)); } catch(OperationCanceledException ex) { //** Never Hit Thrown = true; } sw.Stop(); Assert.True(sw.Elapsed >= TimeSpan.FromMilliseconds(1000)); //** fails nothing is awaited, executes in less than 40ms Assert.True(Thrown); //** Fails } private async Task<T> TimeOut<T>(Func<T> method, TimeSpan timeOut) { using (var ctsForTask = new CancellationTokenSource()) { var taskTimeOut = Task.Delay(timeOut); Task<T> task = Task.Run(() => method(), ctsForTask.Token); if (task != await Task.WhenAny(task, taskTimeOut)) { ctsForTask.Cancel(); throw new OperationCanceledException(ctsForTask.Token); } return task.Result; } }
- 2 回答
- 0 关注
- 81 浏览
添加回答
举报
0/150
提交
取消