I am practicing multitasking and tried this code but it doesn't work as I expected it to.
I was expecting for the the workTask to run first printing "working..." throughout the loop then continue with newTask and print "moreWorkThread: working..." throughout the loop. At first I thought "workThread: Done" will be printed at the end but then I understood from output that it can run anytime between the other ones.
I don't understand the rest of the behaviour at all.
newTask doesn't run at all and the loop in someWork never gets completed either.
Can somebody please explain it to me? I want to know why this code is behaving so and what mods can I make to give expected output
complete loop.
public static void Main() { Task workTask = new Task(someWork); workTask.Start(); Console.WriteLine("WorkThread: Done!"); Task newTask = workTask.ContinueWith(moreWork); } static public void someWork() { for(int i = 0; i < 16; i++) { Console.WriteLine("WorkThread: working..."); } } static public void moreWork(Task task) { for(int i = 0; i < 8; i++) { Console.WriteLine("moreWorkThread: working..."); } }
sample output:
WorkThread: Done!
WorkThread: working...
WorkThread: working...
var task = Task.Run(() =>
{
someWork();
});
await task;
Console.WriteLine("WorkThread: Done!");
await task.ContinueWith((t) => {morework() } );
You'd better use async await. Await will wait for somework to finish executing first before you say "done".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.