Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task return type gives not all code paths return a value

Tags:

c#

I have a method implemented from an interface which looks as follows..

public Task CreateAsync(ApplicationUser user)
{
     if (user == null)
     {
         throw new ArgumentNullException("user");
     }
     Task.Factory.StartNew(() => { Console.WriteLine("Hello Task library!"); }); 
     //I even tried
     //Task.Run(() => { Console.WriteLine("Hello Task library!"); });

}

The above code gives me an error not all code paths return a value.

like image 268
Arnab Avatar asked Jun 30 '16 11:06

Arnab


People also ask

What is not all code paths return a value?

The error "Not all code paths return a value" occurs when some of the code paths in a function don't return a value. To solve the error, make sure to return a value from all code paths in the function or set noImplicitReturns to false in your tsconfig.

Can a task return a value?

Using this Task<T> class we can return data or values from a task. In Task<T>, T represents the data type that you want to return as a result of the task. With Task<T>, we have the representation of an asynchronous method that is going to return something in the future.

What is the return type of task?

The Task<TResult> return type is used for an async method that contains a return statement in which the operand is TResult . In the following example, the GetLeisureHoursAsync method contains a return statement that returns an integer.

How do you set a return value in a task?

Explicitly sets the return value for a task. In a DAG of tasks, a task can call this function to set a return value. Another task that identifies this task as the predecessor task (using the AFTER keyword in the task definition) can retrieve the return value set by the predecessor task.


Video Answer


2 Answers

returning Task.CompletedTask is cleaner.

public Task CreateAsync(ApplicationUser user)
{
  if (user == null)
  {
     throw new ArgumentNullException("user");
  }

   Task.Factory.StartNew(() => { Console.WriteLine("Hello Task library!"); }); 
   // other operations

   return Task.CompletedTask;
 }
like image 195
Mahbubur Rahman Avatar answered Nov 15 '22 21:11

Mahbubur Rahman


Needs a return :

 return Task.Factory.StartNew(() => { Console.WriteLine("Hello Task library!"); });

Or better:

return Task.Run(() => { Console.WriteLine("Hello Task library!"); });
like image 40
Zein Makki Avatar answered Nov 15 '22 20:11

Zein Makki