當Task.Start()
被調用時,如何更新參數currentTime
發送到WriteToConsole
?調用Task.Start()時更新參數值?
在下面的示例中,當我聲明task0
時,currentTime
的值設置爲1/1/2000。當執行task0.Start();
時,currentTime
的值已更改爲DateTime.Now
。但Console.WriteLine
顯示'1/1/2000'。
我需要做些什麼來更新currentTime
,以便使用當前值調用task0.Start()?
static void WriteToConsole(DateTime n)
{
Console.WriteLine(n.ToString());
}
static void Main(string[] args)
{
DateTime currentTime = new DateTime(2000, 01, 01);
Task task0 = new Task(n => WriteToConsole((DateTime)n), currentTime);
for (; ;)
{
currentTime = DateTime.Now;
if (true)
{
task0.Start();
}
if (task0.Status.Equals(TaskStatus.Running))
{
// Do Something
}
}
}
需要更多的上下文。你是否想創建task0的多個實例,每個實例都有自己的currentTime?在這種情況下,每次啓動時都會創建一個新的Task實例。 – 2014-10-01 21:59:38