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

标签 c# .net asynchronous task-parallel-library

我得到的这个程序给我语法错误“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;
            });
    }
}
}

最佳答案

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

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

因为编译器可以推断返回类型,所以这也有效:

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

关于c# - .NET 4.0 中使用 C# 的 Task.Run 的替代方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17607048/

相关文章:

c# - IIS express 中未释放内存使用情况

c# - 如何在 C# 中深度复制包含列表的字典?

c# - 使用 LINQ to SQL 获取刷新的数据

c# - 将 IEnumerable.Aggregate 与异步调用结合使用

c# - 如何区分 .net WebBrowser 组件和实际浏览器?

c# - 如何在 C# (.NET) 中加载 MS Word 文档的文本?

.net - 如何让辅助角色应用程序访问Web角色实例中的文件

.net - 部署.NET 2.0 sp2

javascript - 将 URL 中的数据添加到传单 map

javascript - 获取新数组后组件未更新