2014-04-09 58 views
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的結果相同?有什麼我需要考慮額外?

回答

3

您可以調整您的服務等級,以獲得預期的行爲。

public class Service 
{ 
    private int _called = 0; 
    private Task<int> _asyncTask; 

    public Task<int> DoAsync() 
    { 
     if (!IsFinished) 
      return _asyncTask; 

     _asyncTask = Task.Run(() => Do()); 
     return _asyncTask; 
    } 

    private bool IsFinished 
    { 
     get 
     { 
      return _asyncTask == null || 
        _asyncTask.IsCompleted || 
        _asyncTask.IsCanceled || 
        _asyncTask.IsFaulted; 
     } 
    } 

    private int Do() 
    { 
     System.Threading.Thread.Sleep(200); // fake business. 
     return ++_called; 
    } 
} 
相關問題