Joe_Hendricks
Joe_Hendricks

Reputation: 756

Update parameter value when calling Task.Start()?

How can I update the parameter currentTime being sent to WriteToConsole when Task.Start() is called?

In the example below, When I declare task0, the value of currentTime is set at 1/1/2000. When task0.Start(); is executed, the value of currentTime has changed to DateTime.Now. But Console.WriteLine displays '1/1/2000'.

What would I need to do to update the currentTime so that task0.Start() is called with the current value?

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
        }
    }
}

Upvotes: 0

Views: 68

Answers (2)

h.alex
h.alex

Reputation: 902

encapsulate the parameter in a wrapper class, like this:

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
    }
}

if you have no specific reason for passing the current time as an argument (n => ...), then use ths's answer, it's much nicer factoring.

Upvotes: 0

ths
ths

Reputation: 2942

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

should work, since the variable is captured, not the value.

Upvotes: 1

Related Questions