Running two routine by Task.Run at same time

  • Thread starter Thread starter Sudip_inn
  • Start date Start date
S

Sudip_inn

Guest
see my first set of code.

private async void button1_Click(object sender, EventArgs e)
{
var task1 = Task.Run(() => GetAllTheCats());
var task2 = Task.Run(() => GetAllTheFood());
var result = await Task.WhenAll(task1, task2);
}


public string GetAllTheCats()
{
// Do stuff, like hit the Db, spin around, dance, jump, etc...
// It all takes some time.
Thread.Sleep(1000);
return "cat found";
}

public string GetAllTheFood()
{
// Do more stuff, like hit the Db, nom nom noms...
// It all takes some time.
Thread.Sleep(2000);
return "food found";
}

in the above code i am running two routine at same time by Task.Run. the above two routine is not asynchronous rather synchronous.

in later code set of code i make the above two routine asynchronous and run those function parallel by task.run

private async void button1_Click(object sender, EventArgs e)
{
var task1 = Task.Run(() => GetAllTheCats());
var task2 = Task.Run(() => GetAllTheFood());
var result = await Task.WhenAll(task1, task2);
}

public async Task<string> GetAllTheCats()
{
// Do stuff, like hit the Db, spin around, dance, jump, etc...
// It all takes some time.
await Task.Delay(1000);
return "cat found";
}

public async Task<string> GetAllTheFood()
{
// Do more stuff, like hit the Db, nom nom noms...
// It all takes some time.
await Task.Delay(2000);
return "food found";
}


most important see my two set of code and tell me what would be difference calling two synchronous method by task.run and again calling two asynchronous method by task.run ?

now tell me which approach is good and would be efficient and why ? task.run spawn a new thread ?

async await also create new thread ?



please guide me.

Continue reading...
 
Back
Top