2

This question is trivial and it is for readability. I would just like to know weather the following line of code has any alternative ? Is that code is correct in the means of Readability and style?

Task newTask = new Task(() => { });

EDIT:

This task will be created when certain condition/rule met. In that case i would assign an Action to this class.

if(condition Met && newTask.Status != TaskStatus.Running )
{
  newTask = Task.Factory.StartNew(Action);
  }

Thanks

Rajesh Subramanian
  • 6,400
  • 5
  • 29
  • 42

1 Answers1

1

A Task object is not mean to be run multiple times and started and stopped at will. If you cancel a task or it runs to completion you are meant to create a new Task object the next time you want to execute it again. You can keep a reference to your task object and cancel it using a CancellationTokenSource.

I would suggest simply keeping track of whether the task is running by either a bool variable or a Task variable itself where a null value indicates the task isn't running. For example:

private CancellationTokenSource _tokenSource = new CancellationTokenSource();
private Task _task;

public void StartDoingSomething()
{
    if (_task == null)
    {
        _task = Task.Factory.StartNew(Worker, _tokenSource.Token)
                            .ContinueWith(_ => _task = null);
    }
}

public void StopDoingSomething()
{
    if (_task != null)
    {
        _tokenSource.Cancel();
    }
}

private void Worker()
{
    while (!_tokenSource.IsCancellationRequested)
    {
        // Do some unit of work
    }
}
Trevor Elliott
  • 11,292
  • 11
  • 63
  • 102