.NET 4中的TaskCreationOptions.DenyChildAttach [英] TaskCreationOptions.DenyChildAttach in .NET 4

查看:64
本文介绍了.NET 4中的TaskCreationOptions.DenyChildAttach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到,在.NET 4.5中, Task.Run()等效于

I have seen that in .NET 4.5 that Task.Run() is the equivalent to

Task.Factory.StartNew(someAction, 
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

但是在.NET 4.0中, TaskCreationOptions.DenyChildAttach 不存在.这是 TaskEx.Run 出现的地方吗?此问题中的注释似乎表明了这一点,但未给出详细说明..NET 4.5中用于.NET 4.5的 Task.Run 的等效项是什么?

But in .NET 4.0, TaskCreationOptions.DenyChildAttach does not exist. Is this where TaskEx.Run comes in? A comment in this question seems to indicate that, but no elaboration is given. What is the equivalent in .NET 4.0 for .NET 4.5's Task.Run?

推荐答案

DenyChildAttach 选项不仅在 TaskCreationOptions 枚举中不存在,而且不存在在框架本身中..Net 4.0中不存在实际上会拒绝尝试附加子任务的代码.(更多信息请参见.NET 4.5中的新 TaskCreationOptions TaskContinuationOptions ).

The DenyChildAttach option not only doesn't exist in the TaskCreationOptions enum, it doesn't exist in the framework itself. The code that would actually deny the attempted attachment of a child task doesn't exist in .Net 4.0. (more in New TaskCreationOptions and TaskContinuationOptions in .NET 4.5).

因此,.net 4.0中也不存在 Task.Run exact 等效项.与之最接近的事情是根本不使用该枚举中的 AttachedToParent 值:

So the exact equivalent of Task.Run doesn't and can't exist in .Net 4.0. The closest thing to it would be to simply not use the AttachedToParent value in that enum:

public static Task<TResult> Run<TResult>(Func<TResult> function)
{
    return Task.Factory.StartNew(
        function, 
        CancellationToken.None, 
        TaskCreationOptions.None, 
        TaskScheduler.Default);
}


IMO更为重要的区别是 Task.Run 中对 async 委托的支持.如果将 async 委托(即 Func< Task< TResult>> )传递给 Factory.StartNew ,则会返回像某些人所希望的那样,使用Task< Task< TResult>> 代替 Task< TResult> ,这是 Task ; :


A more important difference IMO is the support for async delegates in Task.Run. If you pass an async delegate (i.e. Func<Task<TResult>>) to Factory.StartNew you get back in return Task<Task<TResult>> instead of Task<TResult> as some would expect which is a source of many headaches. The solution to that is to use the TaskExtensions.Unwrap extension method that "Creates a proxy Task that represents the asynchronous operation of a Task<Task<T>>":

public static Task<TResult> Run<TResult>(Func<Task<TResult>> function)
{
    return Task.Factory.StartNew(
        function, 
        CancellationToken.None, 
        TaskCreationOptions.None, 
        TaskScheduler.Default).Unwrap();
}

这篇关于.NET 4中的TaskCreationOptions.DenyChildAttach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆