使用C#在.NET 4.0中替代Task.Run的方法是什么?


74

我得到了这个程序,该程序给我语法错误“ System.Threading.Tasks.task不包含运行的定义”。

我正在使用VB 2010 .NET 4.0有什么想法?在.net 4.0中运行是否有替代品?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ChatApp
{
class ChatProg
{
    static void Main(string[] args)
    {
        Task<int> wakeUp = DoWorkAsync(2000,"Waking up");
        Task.WaitAll(wakeUp);
    }

    static Task<int> DoWorkAsync(int milliseconds, string name)
    {

        //error appears below on word Run
        return Task.Run(() =>
            {
                Console.WriteLine("* starting {0} work", name);
                Thread.Sleep(milliseconds);
                Console.WriteLine("* {0} work one", name);
                return 1;
            });
    }
}
}

4
试试这个Task.Factory.StartNew()请参考以下链接:blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx
Saroop Trivedi

我遇到了同样的问题,但我在阅读有关此问题时有风险的问题,所以线程选择很好吗?如果是,请向我提供有关线程的详细示例,因为这是我第一次使用线程
sam

Answers:


88

看起来Task.Factory.StartNew<T>就是您所追求的。

return Task.Factory.StartNew<int>(() => {
    // ...
    return 1;
});

由于编译器可以推断返回类型,因此它也可以工作:

return Task.Factory.StartNew(() => {
    // ...
    return 1;
});

2
是运行.NET 4.5功能吗?
Ace Caserya

3
@Henryyottabyte是的,显然是:msdn.microsoft.com/en-us/library/...
McGarnagle

3
我找到的这个链接增加了答案。blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx
Ace Caserya

1
看起来像C:/ CLI中的Task :: Factory-> StartNew
Miroslav Nedyalkov

5
重要的是要知道此代码的行为与Task.Run不同。
usr

10

最高的投票答案,不幸的是,是不完全正确的

不幸的是,StartNew唯一带有TaskScheduler的重载还要求您指定CancellationToken和TaskCreationOptions。这意味着,为了使用Task.Factory.StartNew可靠地,可预测地将工作排队到线程池中,您必须使用如下重载:

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

因此,最接近Task.Run4.0的是:

/// <summary>
/// Starts the new <see cref="Task"/> from <paramref name="function"/> on the Default(usually ThreadPool) task scheduler (not on the TaskScheduler.Current).
/// It is a 4.0 method nearly analogous to 4.5 Task.Run.
/// </summary>
/// <typeparam name="T">The type of the return value.</typeparam>
/// <param name="factory">The factory to start from.</param>
/// <param name="function">The function to execute.</param>
/// <returns>The task representing the execution of the <paramref name="function"/>.</returns>
public static Task<T> StartNewOnDefaultScheduler<T>(this TaskFactory factory, Func<T> function)
{
    Contract.Requires(factory != null);
    Contract.Requires(function != null);

    return factory
        .StartNew(
            function,
            cancellationToken: CancellationToken.None,
            creationOptions: TaskCreationOptions.None,
            scheduler: TaskScheduler.Default);
}

可以像这样使用:

Task
    .Factory
    .StartNewOnDefaultScheduler(() => 
        result);

5

我通过Task.Factory.StartNew检查详细信息链接更改了您的代码

 static Task<int> DoWorkAsync(int milliseconds, string name)
        {


            //error appears below on word Run
            return   Task.Factory.StartNew(() =>
            {
                Console.WriteLine("* starting {0} work", name);
                Thread.Sleep(milliseconds);
                Console.WriteLine("* {0} work one", name);
                return 1;
            });
        }

3

如果您在这里使用Microsoft.Bcl.Async,请执行以下操作:

return TaskEx.Run(() =>
{
    Console.WriteLine("* starting {0} work", name);
    Thread.Sleep(milliseconds);
    Console.WriteLine("* {0} work one", name);
    return 1;
});
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.