Overload Task.Factory.StartNew ()

I have a very simple code:

static void Main(string[] args) { var task = Task.Factory.StartNew(GetInt); var task2 = Task.Factory.StartNew( () => { return GetInt(); }); } static int GetInt() { return 64; } 

Why am I getting a compiler error for the first task? Method signatures (no parameters, int return type) are equal, right?

I know the solution (which is pretty simple: var task = Task.Factory.StartNew<int>(GetInt); ), but I would like to know what the problem is with the above code.

+8
c # compiler-errors task
source share
6 answers

You get an ambiguous call error because the method signature is the same. Return values ​​are not part of the signature.

Since you do not provide an explicit return type, the compiler does not know what to take.

Method signature in C #

+3
source share

Since the compiler cannot decide which of these two overloads to use:

 StartNew(Action) StartNew<TResult>(Func<TResult>) 

The reason for this is that the return type is not part of overload resolution in C # (just as you cannot have two overloads that differ only in return types), and therefore the compiler cannot decide if GetInt a Action or Func<T> . Forcing the use of the generic version by calling StartNew<int>(GetInt) will provide the necessary information.

+3
source share

An exception would help: "The call is ambiguous between the following methods or properties:" System.Threading.Tasks.TaskFactory.StartNew (System.ction) "and" System.Threading.Tasks.TaskFactory.StartNew (System.Func) '"

If you look, there are two possible methods:

 public Task<TResult> StartNew<TResult>(Func<TResult> function); public Task StartNew(Action action); 

If you add <int> or put a Func<int> , you force it to transfer the first signature. Without this, your code is ambiguous.

+1
source share

Here are two more ways to write this (compile):

 var task3 = Task.Factory.StartNew((Func<int>)GetInt); var task4 = Task.Factory.StartNew(() => GetInt()); 
+1
source share

You get a compilation error because the StartNew method accepts either an action (returns void) or Func (returns something) predicates with it various overloads, and not a direct delegate.

0
source share

As pointed out by others, you need to pass GetInt as a function of StartNew or indicate that you intend to return a value from StartNew by providing a generic type. Otherwise, the compiler has no idea what task you intend to create ... this is ambiguous.

 static void Main(string[] args) { var task = Task.Factory.StartNew<int>(GetInt); var task2 = Task.Factory.StartNew( () => { return GetInt(); }); } static int GetInt() { return 64; } 
0
source share

All Articles