Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 调用Task.Start()时更新参数值?_C#_.net_Multithreading - Fatal编程技术网

C# 调用Task.Start()时更新参数值?

C# 调用Task.Start()时更新参数值?,c#,.net,multithreading,C#,.net,Multithreading,调用Task.Start()时,如何更新发送到writeConsole的参数currentTime 在下面的示例中,当我声明task0时,currentTime的值设置为1/1/2000。当task0.Start()时时,currentTime的值已更改为DateTime。现在。但是Console.WriteLine显示“1/1/2000” 我需要做什么来更新currentTime,以便使用当前值调用task0.Start() static void WriteToConsole(DateTim

调用
Task.Start()
时,如何更新发送到
writeConsole
的参数
currentTime

在下面的示例中,当我声明
task0
时,
currentTime
的值设置为1/1/2000。当
task0.Start()时时,
currentTime
的值已更改为
DateTime。现在
。但是
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
        }
    }
}

将参数封装在包装类中,如下所示:

private class DtWrapper
{ 
    public DateTime CurrentTime {get; set; }
}

DtWrapper currentTime = new DtWrapper { CurrentTime = new DateTime(2000, 01, 01) } ;
Task task0 = new Task(n => WriteToConsole(((DtWrapper)n).CurrentTime), currentTime);

for (; ; )
{
    currentTime.CurrentTime = DateTime.Now;
    if (true)
    {
        task0.Start();
    }
    if (task0.Status.Equals(TaskStatus.Running))
    {
        // Do Something
    }
}
如果您没有特定的理由将当前时间作为参数传递(n=>…),那么使用ths的答案,这是更好的因式分解

Task task0 = new Task(() => WriteToConsole(currentTime));

应该可以,因为捕获的是变量,而不是值。

需要更多的上下文。是否要创建多个task0实例,每个实例都有自己的currentTime?在这种情况下,您将希望在每次启动任务实例时创建一个新的任务实例。如果“捕获的是变量,而不是值”,则DateTime是不可变的,并且捕获的变量将始终指向同一个不可变对象。调用
currentTime=[some new DateTime]
不会更改原始的不可变对象,而只是重新分配
currentTime
指向的对象(但任务捕获的变量仍将指向旧的不可变对象)。