Task vs async Task when running multiple task in background [duplicate]





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0
















This question already has an answer here:




  • What is the purpose of “return await” in C#?

    7 answers




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()));
//}
}


What's the difference?
enter image description here










share|improve this question















marked as duplicate by Servy .net
Users with the  .net badge can single-handedly close .net questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 26 '18 at 17:10


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • 1





    1. Task.Run(() => DoSomeAsyncStuff("a")); will block the execution - it shouldn't block an execution. Main will continue execution regardless of that call result.

    – Fabio
    Nov 25 '18 at 5:44






  • 2





    Are you sure about that last comment, @Fabio? Aren't you confusing the state machine with the synchronization context?

    – Paulo Morgado
    Nov 25 '18 at 22:03











  • @PauloMorgado, StateMachine it is, thanks

    – Fabio
    Nov 26 '18 at 5:52


















0
















This question already has an answer here:




  • What is the purpose of “return await” in C#?

    7 answers




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()));
//}
}


What's the difference?
enter image description here










share|improve this question















marked as duplicate by Servy .net
Users with the  .net badge can single-handedly close .net questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 26 '18 at 17:10


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • 1





    1. Task.Run(() => DoSomeAsyncStuff("a")); will block the execution - it shouldn't block an execution. Main will continue execution regardless of that call result.

    – Fabio
    Nov 25 '18 at 5:44






  • 2





    Are you sure about that last comment, @Fabio? Aren't you confusing the state machine with the synchronization context?

    – Paulo Morgado
    Nov 25 '18 at 22:03











  • @PauloMorgado, StateMachine it is, thanks

    – Fabio
    Nov 26 '18 at 5:52














0












0








0









This question already has an answer here:




  • What is the purpose of “return await” in C#?

    7 answers




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()));
//}
}


What's the difference?
enter image description here










share|improve this question

















This question already has an answer here:




  • What is the purpose of “return await” in C#?

    7 answers




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()));
//}
}


What's the difference?
enter image description here





This question already has an answer here:




  • What is the purpose of “return await” in C#?

    7 answers








c# .net multithreading async-await task






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 26 '18 at 17:02







Pawel Cioch

















asked Nov 25 '18 at 4:53









Pawel CiochPawel Cioch

1,59811724




1,59811724




marked as duplicate by Servy .net
Users with the  .net badge can single-handedly close .net questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 26 '18 at 17:10


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by Servy .net
Users with the  .net badge can single-handedly close .net questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 26 '18 at 17:10


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.










  • 1





    1. Task.Run(() => DoSomeAsyncStuff("a")); will block the execution - it shouldn't block an execution. Main will continue execution regardless of that call result.

    – Fabio
    Nov 25 '18 at 5:44






  • 2





    Are you sure about that last comment, @Fabio? Aren't you confusing the state machine with the synchronization context?

    – Paulo Morgado
    Nov 25 '18 at 22:03











  • @PauloMorgado, StateMachine it is, thanks

    – Fabio
    Nov 26 '18 at 5:52














  • 1





    1. Task.Run(() => DoSomeAsyncStuff("a")); will block the execution - it shouldn't block an execution. Main will continue execution regardless of that call result.

    – Fabio
    Nov 25 '18 at 5:44






  • 2





    Are you sure about that last comment, @Fabio? Aren't you confusing the state machine with the synchronization context?

    – Paulo Morgado
    Nov 25 '18 at 22:03











  • @PauloMorgado, StateMachine it is, thanks

    – Fabio
    Nov 26 '18 at 5:52








1




1





1. Task.Run(() => DoSomeAsyncStuff("a")); will block the execution - it shouldn't block an execution. Main will continue execution regardless of that call result.

– Fabio
Nov 25 '18 at 5:44





1. Task.Run(() => DoSomeAsyncStuff("a")); will block the execution - it shouldn't block an execution. Main will continue execution regardless of that call result.

– Fabio
Nov 25 '18 at 5:44




2




2





Are you sure about that last comment, @Fabio? Aren't you confusing the state machine with the synchronization context?

– Paulo Morgado
Nov 25 '18 at 22:03





Are you sure about that last comment, @Fabio? Aren't you confusing the state machine with the synchronization context?

– Paulo Morgado
Nov 25 '18 at 22:03













@PauloMorgado, StateMachine it is, thanks

– Fabio
Nov 26 '18 at 5:52





@PauloMorgado, StateMachine it is, thanks

– Fabio
Nov 26 '18 at 5:52












1 Answer
1






active

oldest

votes


















-1














The async keyword will instruct the compiler to build a state machine with being the code between the beginning of the method' execution flow and the first await, the code between any two consecutive awaits and between the last await and the return of the method.



The return type of the method is either void if you don't care about the result or if the method completes (beware of this), Task if you want to await the execution of the method but don't want to return any value or Task<T> if you want to await the execution of the method and return a value of type T.



If the method doesn't have the async modifier, than it's just a "normal" method.






share|improve this answer
























  • but private Task DoSomeAsyncStuff doesn't have async keyword and runs async, all the methods finish first before text == "0" where the thread sleeps. I'm assuming you referred to any method that has a type different than Task

    – Pawel Cioch
    Nov 26 '18 at 16:52











  • No it doesn't! It invokes something that runs async and returns the task representing that.

    – Paulo Morgado
    Nov 26 '18 at 22:34











  • It does, and I made the proof for you github.com/skironDotNet/AsyncBackgroundTask

    – Pawel Cioch
    Nov 27 '18 at 17:16













  • No it doesn't, and you proved nothing: github.com/skironDotNet/AsyncBackgroundTask/issues/1

    – Paulo Morgado
    Nov 28 '18 at 22:14


















1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









-1














The async keyword will instruct the compiler to build a state machine with being the code between the beginning of the method' execution flow and the first await, the code between any two consecutive awaits and between the last await and the return of the method.



The return type of the method is either void if you don't care about the result or if the method completes (beware of this), Task if you want to await the execution of the method but don't want to return any value or Task<T> if you want to await the execution of the method and return a value of type T.



If the method doesn't have the async modifier, than it's just a "normal" method.






share|improve this answer
























  • but private Task DoSomeAsyncStuff doesn't have async keyword and runs async, all the methods finish first before text == "0" where the thread sleeps. I'm assuming you referred to any method that has a type different than Task

    – Pawel Cioch
    Nov 26 '18 at 16:52











  • No it doesn't! It invokes something that runs async and returns the task representing that.

    – Paulo Morgado
    Nov 26 '18 at 22:34











  • It does, and I made the proof for you github.com/skironDotNet/AsyncBackgroundTask

    – Pawel Cioch
    Nov 27 '18 at 17:16













  • No it doesn't, and you proved nothing: github.com/skironDotNet/AsyncBackgroundTask/issues/1

    – Paulo Morgado
    Nov 28 '18 at 22:14
















-1














The async keyword will instruct the compiler to build a state machine with being the code between the beginning of the method' execution flow and the first await, the code between any two consecutive awaits and between the last await and the return of the method.



The return type of the method is either void if you don't care about the result or if the method completes (beware of this), Task if you want to await the execution of the method but don't want to return any value or Task<T> if you want to await the execution of the method and return a value of type T.



If the method doesn't have the async modifier, than it's just a "normal" method.






share|improve this answer
























  • but private Task DoSomeAsyncStuff doesn't have async keyword and runs async, all the methods finish first before text == "0" where the thread sleeps. I'm assuming you referred to any method that has a type different than Task

    – Pawel Cioch
    Nov 26 '18 at 16:52











  • No it doesn't! It invokes something that runs async and returns the task representing that.

    – Paulo Morgado
    Nov 26 '18 at 22:34











  • It does, and I made the proof for you github.com/skironDotNet/AsyncBackgroundTask

    – Pawel Cioch
    Nov 27 '18 at 17:16













  • No it doesn't, and you proved nothing: github.com/skironDotNet/AsyncBackgroundTask/issues/1

    – Paulo Morgado
    Nov 28 '18 at 22:14














-1












-1








-1







The async keyword will instruct the compiler to build a state machine with being the code between the beginning of the method' execution flow and the first await, the code between any two consecutive awaits and between the last await and the return of the method.



The return type of the method is either void if you don't care about the result or if the method completes (beware of this), Task if you want to await the execution of the method but don't want to return any value or Task<T> if you want to await the execution of the method and return a value of type T.



If the method doesn't have the async modifier, than it's just a "normal" method.






share|improve this answer













The async keyword will instruct the compiler to build a state machine with being the code between the beginning of the method' execution flow and the first await, the code between any two consecutive awaits and between the last await and the return of the method.



The return type of the method is either void if you don't care about the result or if the method completes (beware of this), Task if you want to await the execution of the method but don't want to return any value or Task<T> if you want to await the execution of the method and return a value of type T.



If the method doesn't have the async modifier, than it's just a "normal" method.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 25 '18 at 22:10









Paulo MorgadoPaulo Morgado

6,41011633




6,41011633













  • but private Task DoSomeAsyncStuff doesn't have async keyword and runs async, all the methods finish first before text == "0" where the thread sleeps. I'm assuming you referred to any method that has a type different than Task

    – Pawel Cioch
    Nov 26 '18 at 16:52











  • No it doesn't! It invokes something that runs async and returns the task representing that.

    – Paulo Morgado
    Nov 26 '18 at 22:34











  • It does, and I made the proof for you github.com/skironDotNet/AsyncBackgroundTask

    – Pawel Cioch
    Nov 27 '18 at 17:16













  • No it doesn't, and you proved nothing: github.com/skironDotNet/AsyncBackgroundTask/issues/1

    – Paulo Morgado
    Nov 28 '18 at 22:14



















  • but private Task DoSomeAsyncStuff doesn't have async keyword and runs async, all the methods finish first before text == "0" where the thread sleeps. I'm assuming you referred to any method that has a type different than Task

    – Pawel Cioch
    Nov 26 '18 at 16:52











  • No it doesn't! It invokes something that runs async and returns the task representing that.

    – Paulo Morgado
    Nov 26 '18 at 22:34











  • It does, and I made the proof for you github.com/skironDotNet/AsyncBackgroundTask

    – Pawel Cioch
    Nov 27 '18 at 17:16













  • No it doesn't, and you proved nothing: github.com/skironDotNet/AsyncBackgroundTask/issues/1

    – Paulo Morgado
    Nov 28 '18 at 22:14

















but private Task DoSomeAsyncStuff doesn't have async keyword and runs async, all the methods finish first before text == "0" where the thread sleeps. I'm assuming you referred to any method that has a type different than Task

– Pawel Cioch
Nov 26 '18 at 16:52





but private Task DoSomeAsyncStuff doesn't have async keyword and runs async, all the methods finish first before text == "0" where the thread sleeps. I'm assuming you referred to any method that has a type different than Task

– Pawel Cioch
Nov 26 '18 at 16:52













No it doesn't! It invokes something that runs async and returns the task representing that.

– Paulo Morgado
Nov 26 '18 at 22:34





No it doesn't! It invokes something that runs async and returns the task representing that.

– Paulo Morgado
Nov 26 '18 at 22:34













It does, and I made the proof for you github.com/skironDotNet/AsyncBackgroundTask

– Pawel Cioch
Nov 27 '18 at 17:16







It does, and I made the proof for you github.com/skironDotNet/AsyncBackgroundTask

– Pawel Cioch
Nov 27 '18 at 17:16















No it doesn't, and you proved nothing: github.com/skironDotNet/AsyncBackgroundTask/issues/1

– Paulo Morgado
Nov 28 '18 at 22:14





No it doesn't, and you proved nothing: github.com/skironDotNet/AsyncBackgroundTask/issues/1

– Paulo Morgado
Nov 28 '18 at 22:14





這個網誌中的熱門文章

Xamarin.form Move up view when keyboard appear

Post-Redirect-Get with Spring WebFlux and Thymeleaf

Anylogic : not able to use stopDelay()