Thread synchronization is not important to me. I just want to understand if there is any specific difference. So can someone review this code and give me some ideas. All methods are executed in the background as desired I just
Part 1.
In Program DoSomeAsyncStuff()
when removed async
then
Task.Run(() => DoSomeAsyncStuff("a"));
will block the execution, so I need async,
Compare DoSomeAsyncStuff
to DoSomeAsyncStuffV2
is once implementation preferred over another?
UPDATE: Let's focus on
Part 2.
whats the difference private async Task Do..()
vs private Task Do..()
based on this https://stackoverflow.com/a/48392684/1818723 I think there could be none, but if you look at both methods implementation, one is awaiting for task to complete and the other is returning the task
public class ServiceX
{
public Task SomeServiceEntryMethod()
{
Console.WriteLine("Multithreading started");
Thread.Sleep(1);
List<Task> tasks = new List<Task>();
for (int i = 0; i < 8; i++)
{
//I can use this version
//var t = DoSomeAsyncStuff(i.ToString());
//or I can use this version both seems to have same results
var t = DoSomeAsyncStuffV2(i.ToString());
tasks.Add(t);
}
//in the calling method I can await for all task to complete the for loop spins a few async tasks
return Task.WhenAll(tasks);
}
private async Task DoSomeAsyncStuffV2(string text)
{
await Task.Run(() =>
{
if (text == "0")
Thread.Sleep(1000);
Console.WriteLine("test " + text + " " + Thread.CurrentThread.ManagedThreadId.ToString());
});
}
private Task DoSomeAsyncStuff(string text)
{
return Task.Run(() =>
{
if (text == "0")
Thread.Sleep(1000);
Console.WriteLine("test " + text + " " + Thread.CurrentThread.ManagedThreadId.ToString());
});
}
}
class Program
{
public static async Task Main(string[] args)
{
//Task.Run(() => DoSomeAsyncStuff("a"));
//Task.Run(() => DoSomeAsyncStuff("b"));
//DoSomeAsyncStuffV2("c");
//DoSomeAsyncStuffV2("d");
ServiceX x = new ServiceX();
await x.SomeServiceEntryMethod();
}
//private static async void DoSomeAsyncStuff(string text)
//{
//Console.WriteLine("test " + text + " " + Thread.CurrentThread.ManagedThreadId.ToString());
//}
//private static async void DoSomeAsyncStuffV2(string text)
//{
//await Task.Run(() => Console.WriteLine("test " + text + " " + Thread.CurrentThread.ManagedThreadId.ToString()));
//}
}