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

Ace Caserya picture Ace Caserya · Jul 12, 2013 · Viewed 48.2k times · Source

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

Answer

McGarnagle picture McGarnagle · Jul 12, 2013

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