我創建了一個任務併爲task.wait()方法提供了等待時間,但是任務沒有等到所提供的時間,並且在等待時間之前返回完成狀態爲false。任務沒有等到等待時間
using System;
using System.Threading;
using System.Threading.Tasks;
class Test
{
static void Main(string[] args)
{
for(int i = 0 ; i < 10 ; i++)
{
int localValue = i;
Task.Factory.StartNew(() => ProcessTask(localValue));
}
Console.ReadKey();
}
private static void ProcessTask(int thread)
{
var task = Task<int>.Factory.StartNew(() => GetSomeValue());
task.Wait(2000);
if(task.IsCompleted)
{
Console.WriteLine("Completed Thread: " + thread);
}
else
{
Console.WriteLine("Not Completed Thread " + thread);
}
}
private static int GetSomeValue()
{
Thread.Sleep(400);
return 5;
}
}
更新:
我已經更新了代碼。當我運行這個代碼時,我得到了以下輸出。
只有兩個任務都完成了的10,所以我想知道什麼是與此代碼的問題?
注:我在4.5.2框架中運行此代碼。
假如你試圖給'Tuple'變量賦一個'int'值,它看起來並不像代碼甚至會編譯。請提供[mcve]。 (我也建議使用'Task.Run'而不是'TaskFactory.StartNew' ...) –
@ JonSkeet-由於錯誤的Tuple被添加。我更新了代碼。而我正在使用4.0框架,所以運行該方法不可用。 – Girish
這些信息值得一提,因爲這幾天需要4.0是多麼罕見......而且你還沒有發佈[mcve],這會讓你更容易幫助你。 –