Trying to achieve Fire and Forget:
class Program
{
static void Main(string[] args)
{
var my = new MyClass();
my.OrderForm_Load();
Console.ReadLine();
}
}
internal class MyClass
{
//Blocking
public void OrderForm_Load()
{
var t1 = new ServiceTask();
Task.Run(() => t1.PersistTask()); //Approach 1:
//[OR]
t1.PersistTask(); //Approach 2: Has compiler errors CS4014
Console.WriteLine("Second");
}
}
internal class ServiceTask
{
//Non-Blocking
public async Task PersistTask()
{
var resultTask = Task.Run(() =>
{
Thread.Sleep(3000);
Console.WriteLine("First");
return Task.FromResult(0);
});
await resultTask;
}
}
Between the Approach 1 and Approach 2; I prefer the Approach 1. Is there any other better way to call PersistTask() from OrderForm_Load() method? I have a colleague who is hesitant to use Task.Run but want to find out if there is any other better way.
The objective is, we want "second" to be printed ASAP and need not to worry about the method that prints "first". Fire and Forget.