[英]Task does not contain a definition for Run method
I tried to implement multithreading in my code, 1st time. 我第一次尝试在我的代码中实现多线程。 When i tried to use
当我试图使用
Task T = Task.Run(() => { });
Visual Studio is still underlines Run() with statement "Task does not contain a definition 'Run' " Visual Studio仍然使用语句“任务不包含定义'运行'”强调Run()
I'm using System.Threading.Tasks; 我正在使用System.Threading.Tasks; Internet knows nothing about this problem
互联网对此问题一无所知
Unfortunately, is not exactly correct that Task.Run
is same as Task.Factory.StartNew
. 不幸的是,
Task.Run
与Task.Factory.StartNew
相同并不完全正确 。
In this answer , it is given the closest thing to Task.Run
in 4.0 which is something like: 在这个答案中,它给出了最接近于4.0的
Task.Run
,它是这样的:
/// <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);
But Task.Run
is a nice wrapper over Task.Factory.StartNew
introduced in .NET 4.5
. 但是
Task.Run
是一个很好的包装上Task.Factory.StartNew
在介绍.NET 4.5
。
But for your situation, when you need it for multithreading
operations, just use it. 但是对于您的情况,当您需要
multithreading
操作时,只需使用它即可。
But don't forget.
但别忘了。
You should prefer Task.Run
over Task.Factory.StartNew
if you use async
code. 如果使用
async
代码,则应该Task.Run
使用Task.Run
不是Task.Factory.StartNew
。
In this article , Stephen Curry gives two reason that StartNew
method is dangerous: 在本文中 ,Stephen Curry给出了
StartNew
方法危险的两个原因:
Task.Run was introduced in .NET 4.5, you are using .net 4.0. Task.Run是在.NET 4.5中引入的,您使用的是.net 4.0。 If you can't upgrade your project you can include the Microsoft.Bcl.Async NuGet package to introduce a
TaskEx.Run(
to add it in to .net 4.0. 如果无法升级项目,可以包含Microsoft.Bcl.Async NuGet包以引入
TaskEx.Run(
将其添加到.net 4.0中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.