1
我有下面的代碼片斷失敗。當兩次調用函數時,確保C#異步任務返回的最佳方式是什麼?
public class Service
{
private int _called = 0;
public Task<int> DoAsync()
{
return Task.Run(() => Do());
}
private int Do()
{
System.Threading.Thread.Sleep(200); // fake business.
return ++_called;
}
}
public class AsyncTaskTests
{
[Test]
public async Task When_calling_async_function_twice_then_first_task_should_be_returned()
{
var sut = new Service();
var t1 = sut.DoAsync();
var t2 = sut.DoAsync();
await Task.WhenAll(t1, t2);
Assert.That(t1.Result, Is.EqualTo(1));
Assert.That(t2.Result, Is.EqualTo(1));
}
}
如何確保t1和t2的結果相同?有什麼我需要考慮額外?