什么是使用C#.NET 4.0中的Task.Runreplace方法?
我得到这个程序,给我语法错误“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; });
由于编译器可以推断返回types,所以也可以这样做:
return Task.Factory.StartNew(() => { // ... return 1; });
阅读: http : //blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx
它解释说,Task.Run基本上是4.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; }); }
不幸的是, 答案最高的答案并不完全正确 :
不幸的是,使用TaskScheduler的StartNew的唯一重载也需要您指定CancellationToken和TaskCreationOptions。 这意味着为了使用Task.Factory.StartNew来可靠地预测队列工作到线程池,你必须使用这样的过载:
Task.Factory.StartNew(A,CancellationToken.None,TaskCreationOptions.DenyChildAttach,TaskScheduler.Default);
所以在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); }
可以像这样使用:
Task .Factory .StartNewOnDefaultScheduler(() => result);
Task.Factory.StartNew(() => { try { Thread.Sleep(200); IntPtr TouchhWnd = IntPtr.Zero; TouchhWnd = FindWindow(null, "屏幕键盘"); if (TouchhWnd != IntPtr.Zero) { SetWindowPos(TouchhWnd, HWND_TOPMOST, 500, 500, 400, 300, SWP_SHOWWINDOW); } } catch { } });