2016-06-09 42 views
2

如何延遲任務直到返回變量值並且如果超出延遲時間,則變量的值返回null。例如:如果超過延遲時間,則延遲任務並返回空值

TaskA.Delay(5000); 

if variable not equal to empty string 
continue with Task A 

else 
if delay time not exceeded yet 

continue running the current task 
else 

set variable's value to empty string 
+0

請提供更多信息。這個變量是什麼?誰改變了它的價值?你想要延遲的任務在哪裏? –

+0

要麼在單獨的線程中運行它,並在超過時間時將其殺死,要麼可以經常檢查獲取變量的時間。這完全取決於你需要什麼。 – Claudius

+0

@Claudius線程?爲什麼你會爲這麼簡單的事情提出一個全新的線索。如果任務不能在單獨的線程上運行,該怎麼辦?如果你需要使用非阻塞I/O(提示一個線程使用〜1MB的RAM,1000線程會佔用1GB以上的RAM)並行執行數以千計的操作。 – Aron

回答

1

關鍵是要啓動一個「延遲」的任務,並與你的「真實」的任務同時運行它,看看哪一個完成第一:

public async Task<int?> ValueOrNull() 
{ 
    var task = SomeAsyncMethod() //--> the work to wait on 
    var timeout = Task.Delay(new TimeSpan(0,0,5)); 
    var first = await Task.WhenAny(task, timeout); 
    if (first == timeout) return null; 
    await first; //--> It's already done, but let it throw any exception here 
    return; 
} 

您可以通過推廣這個通過你的任務和超時:

public async Task<T> ValueOrNull(Task<T> task, TimeSpan patience) 
{ 
    var timeout = Task.Delay(patience); 
    var first = await Task.WhenAny(task, timeout); 
    if (first == timeout) return default(T); 
    await first; //--> It's already done, but let it throw any exception here 
    return; 
} 
0

有一個更清潔的方式來實施克萊的方法。

public Task<int?> ValueOrNull() 
{ 
    return Task.WhenAny(
     SomeAsyncMethod(), 
     DelayResult(default(int?), TimeSpan.FromSeconds(5)) 
    ); 
} 

public async Task<T> DelayResult<T>(T result, TimeSpan delay) 
{ 
    await Task.Delay(delay); 
    return result; 
}