简体   繁体   English

在TPL中返回一个空的静态任务是一种不好的做法?

[英]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. 我的期望是,theEmptyTask已经完成,所以基本上如果我不想做任何事情我只返回这个任务,而不是null或一个新的空任务。

I have a feeling that there should be some glitch with this approach. 我觉得这种方法应该有一些小问题。 Can anyone see that? 有人能看到吗?

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. 请注意,如果要返回已完成的任务,可以使用Task.FromResult生成一个比现在正在执行的更少的开销,因为您不会创建一个空方法,安排它,等待它开始,然后立即完成。 Just returning Task.FromResult(false) will give you an already completed task. 只返回Task.FromResult(false)将为您提供已完成的任务。

If you are using .NET 4.0 you can create your own FromResult easily enough: 如果您使用的是.NET 4.0,则可以轻松地创建自己的FromResult:

public static Task FromResult<T>(T result)
{
    var tcs = new TaskCompletionSource<T>();
    tcs.SetResult(result);
    return tcs.Task;
}

As long as you hand back a task that is in the completed state (use TaskCompletionSource to do this), I can't think of any problem with this since there aren't really any setters on the Task class that would allow the client to muck with your static empty task. 只要您回退一个处于已完成状态的任务(使用TaskCompletionSource来执行此操作),我就不会想到这有任何问题,因为Task类上实际上没有任何setter允许客户端捣乱你的静态空任务。 They could call Dispose() on your task, but I don't think that would cause any harm (ie I don't think it would affect the ability to inspect the properties of the Task (haven't tried it out--something worth testing out)). 他们可以在你的任务上调用Dispose() ,但我认为这不会造成任何伤害(即我认为它不会影响检查任务属性的能力(没有尝试过 - 某些东西)值得测试))。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM