Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is returning an empty static task in TPL a bad practice?

There are cases that I would want to run a task conditionally. I use some sort of extension method like this:

public static class MyTaskExtension{
  private static Task theEmptyTask = Task.Factory.StartNew(() => {}); //This is the question

  public static Task ContinueWith(this Task task, Task continuationTask, Func<bool> condition)
  {
    if condition(){
       ... do the work
    }
    return theEmptyTask;
  }
}

My expectation is that theEmptyTask would be already completed, so basically if I don't want to do anything I just return this task, instead of null or a new empty task.

I have a feeling that there should be some glitch with this approach. Can anyone see that?

like image 902
naiem Avatar asked Mar 22 '13 04:03

naiem


People also ask

Can Task return null?

You can certainly pass back null from a task.

Can async method return null?

Task represents the execution of the asynchronous method, so for an asynchronous method to return a null task is like telling the calling code "you didn't really just call this method" when of course it did. So, a Task / Task<T> returned from a method should never, ever be null .

How is TPL different from thread?

Compared to the classic threading model in . NET, Task Parallel Library minimizes the complexity of using threads and provides an abstraction through a set of APIs that help developers focus more on the application program instead of focusing on how the threads will be provisioned.


1 Answers

It's perfectly acceptable to return an already completed task in some contexts. It's not something that is done particularly often, but it is done.

There's also nothing wrong at all with just using a single static completed task. There is no need to have a whole bunch of different tasks that are all identical, given that once they're completed, and if they have no result, there's nothing wrong with reusing them.

Note that if you want to return an already completed task you can use Task.FromResult to generate one with less overhead than what you're doing now, as you won't be creating an empty method, scheduling it, waiting for it to be started, and then have it finish right away. Just returning Task.FromResult(false) will give you an already completed task.

If you are using .NET 4.0 you can create your own FromResult easily enough:

public static Task FromResult<T>(T result)
{
    var tcs = new TaskCompletionSource<T>();
    tcs.SetResult(result);
    return tcs.Task;
}
like image 113
Servy Avatar answered Oct 24 '22 06:10

Servy