How to return Task and Task<T> in asynchronous function.
Return Task and Task<T> in asynchronous function
In this article we will learn how to return Task and
Task<T> in asynchronous function. We know that there are three possible return
types of asynchronous function. Those
are
In this tutorial we will learn how to return Task and
Task<T> in asynchronous function.
Return Task in asynchronous function.
In this example we will see how to return Task in
asynchronous function. If we return Task then we can use await keyword to call
any long process function. Have a look on below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace Asynchronious
{
class TestAsync
{
public Task LongTask()
{
return Task.Run(() => {
System.Threading.Thread.Sleep(5000);
});
}
public async void AsyncroniousFunction()
{
await LongTask();
Console.WriteLine("Long Process Finish");
}
}
class Program
{
public static void Main(String[] args)
{
TestAsync obj = new TestAsync();
obj.AsyncroniousFunction();
Console.WriteLine("Program Finish");
Console.ReadLine();
}
}
}
Here is sample output.

We are seeing that LongTask() function is returning Task to its
caller function. As we are calling the function asynchronously the Main()
function is executing at first and it’s not waiting for LongTask() function.
Return Task<T> in asynchronous function.
I hope all of you familiar with T. Yes, T represents any
Type. In this example we will return
string to caller function. Have a look on below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace Asynchronious
{
class TestAsync
{
public Task<string> LongTask()
{
return Task.Run(() => {
System.Threading.Thread.Sleep(5000);
return "Long Process finished";
});
}
public async void AsyncroniousFunction()
{
string value = await LongTask();
Console.WriteLine(value);
}
}
class Program
{
public static void Main(String[] args)
{
TestAsync obj = new TestAsync();
obj.AsyncroniousFunction();
Console.WriteLine("Program
Finish");
Console.ReadLine();
}
}
}
As we are returning string we can able to store it in normal
string variable. And we are printing it. Again we are seeing that Main()
function is not waiting for LongTask() function. At first Main() function
is executing them LongTask() function is
getting executed.
Here is sample output.

Conclusion:-
In this article we have seen how to return Task
and Task<T> in asynchronous function. Hope you have understood the concept. In next few articles we will discuss more on same topic.