Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a replacement method for Task.Run in .NET 4.0 using C#?

I got this program that gives me syntax error "System.Threading.Tasks.task does not contain a definition for Run."

I am using VB 2010 .NET 4.0 Any ideas? any replacements for Run in .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;             });     } } } 
like image 780
Ace Caserya Avatar asked Jul 12 '13 03:07

Ace Caserya


People also ask

What is Task run method in C#?

The Run method allows you to create and execute a task in a single method call and is a simpler alternative to the StartNew method. It creates a task with the following default values: Its cancellation token is CancellationToken.

How do I create a new Task in C#?

To start a task in C#, follow any of the below given ways. Use a delegate to start a task. Task t = new Task(delegate { PrintMessage(); }); t. Start();

When should I use Task run C#?

You should use Task. Run , but not within any code you want to be reusable (i.e., library code). So you use Task. Run to call the method, not as part of the implementation of the method.

What is Task factory StartNew in C#?

StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler.


2 Answers

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; }); 
like image 55
McGarnagle Avatar answered Sep 27 '22 21:09

McGarnagle


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); 
like image 22
Eugene Podskal Avatar answered Sep 27 '22 21:09

Eugene Podskal