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

我得到了这个程序,它给出了语法错误“ System.Threading.Tasks.task 不包含 Run 的定义”

我使用的是 VB 2010. NET 4.0 有什么想法吗? 有没有什么可以替代.net 4.0中的 Run?

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;
});
}
}
}
53013 次浏览

It looks like Task.Factory.StartNew<T> is what you're after.

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

Since the compiler can infer the return type, this also works:

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

I changed your code with Task.Factory.StartNew check detail link

 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;
});
}

The highest voted answer, unfortunately, is not exactly correct:

Unfortunately, the only overloads for StartNew that take a TaskScheduler also require you to specify the CancellationToken and TaskCreationOptions. This means that in order to use Task.Factory.StartNew to reliably, predictably queue work to the thread pool, you have to use an overload like this:

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

So the closest thing to Task.Run in 4.0 is something like:

/// <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);
}

that can be used like:

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

In case you're using Microsoft.Bcl.Async here you go:

return TaskEx.Run(() =>
{
Console.WriteLine("* starting {0} work", name);
Thread.Sleep(milliseconds);
Console.WriteLine("* {0} work one", name);
return 1;
});