Imagine an initialization task and two workers:
var Init = Task.Run(async () =>
{
await Task.Delay(1000);
});
var TaskB = Task.Run(async () =>
{
await Init;
Console.WriteLine("B finished waiting");
await Task.Delay(10000000);
});
var TaskC = Task.Run(async () =>
{
await Init;
Console.WriteLine("C finished waiting");
await Task.Delay(10000000);
});
After 1 second, TaskB and TaskC are printing to the console and continuing as expected.
However, when the task which finishes first uses no asynchronous methods after awaiting Init, the other task await Init call does not finish:
var Init = Task.Run(async () =>
{
await Task.Delay(1000);
});
var TaskB = Task.Run(async () =>
{
await Init;
Console.WriteLine("B finished waiting");
await Task.Delay(5000);
});
var TaskC = Task.Run(async () =>
{
await Init;
Console.WriteLine("C finished waiting");
while (true) { }
});
The latter example prints only "C finished waiting" to the console. Why is that so?
Behind the scenes, async/await builds a state machine based on task continuations. You can mimic it using ContinueWith and a bit of ingenuity (the details are beyond the scope of this answer).
What you need to know is that it uses continuations, and that continuations - by default - happen syncrhonously, one at a time.
In this case, both B and C are creating continuations on Init. These continuations will run after the other. Thus, when C continues first and goes into the infinite loop, it prevents B to continue.
The solution? Well, other than avoiding infinite loops, you could use a task with asynchronous continuations. A simple way to do it on top of Task.Run is the following:
var Init = Task.Run(async () =>
{
await Task.Delay(1000);
}).ContinueWith(_ => { }, TaskContinuationOptions.RunContinuationsAsynchronously);
Addendum
As per OP comment, the infinite loop represent a blocking call. We can solve that situation by a different approach:
var TaskC = Task.Run(async () =>
{
await Init;
Console.WriteLine("C finished waiting");
await Task.Run(() => {while (true) { }});
});
This way, the blocking call is not int the continuation of Init (instead, it would be in a continuation of a continuation), and thus it won't prevent other continuations of Init to run.
Related
See example codes.
Console.WriteLine("start")
Task.Run(async () =>
{
await Task.Delay(3000);
});
Console.WriteLine("end");
// result
// start [3s delay] end
It works!
but below code is not working.
Action action = async () =>
{
await Task.Delay(3000);
};
Console.WriteLine("start")
Task.Run(action);
Console.WriteLine("end");
// result
// start [without delay] end
Why Task.Run does not await async action variable?
edit -------------------------
I'm so sorry. I wrote wrong code.
This is right code.
I test it on C# Interactive of VS 2017
Console.WriteLine("start");
await Task.Run(async () =>
{
await Task.Delay(3000);
});
Console.WriteLine("end");
Action action = async () =>
{
await Task.Delay(3000);
};
Console.WriteLine("start");
await Task.Run(action);
Console.WriteLine("end");
The main reason to use async and Tasks, is to make two or more methods to run simultaneously. So your method will continue running and when finished the delay, will call anything after the delay since you run another async func in a task.
If you run this method, You'll notice
finished
will be printed in the middle of the other work ( and here the other work is for loop,
Console.WriteLine("start");
Task.Run(async () =>
{
await Task.Delay(200);
Console.WriteLine("Finished");
});
for(int i = 0; i < 500; i++)
{
Console.WriteLine(i);
}
Console.WriteLine("end");
Console.ReadKey();
For some reason, It doesn't work as expected on dotnetfiddle
Even if you didn't run async in the task, they will run simultaneously.
Look at this example :
Console.WriteLine("start");
Task.Run(() =>
{
Task.Delay(2000).Wait(); // Will NOT wait !
Console.WriteLine("Finished");
});
for(int i = 0; i < 500; i++)
{
Console.WriteLine(i);
}
Console.WriteLine("end");
Console.ReadKey();
It'll continue without any delay since it's on a Task
But if you want the method to wait, First : Don't run it on a Task.
Second : call the Wait() method.
Like :
Console.WriteLine("start");
Task.Delay(2000).Wait(); // It'll wait for 2 seconds before continue.
for(int i = 0; i < 500; i++)
{
Console.WriteLine(i);
}
Console.WriteLine("end");
Console.ReadKey();
When using Task.Run without an await, this will just 'fire and forget'. Code execution will not wait for it, and it will simply run it as soon as a thread is available from the thread pool.
Typically, if you want to off load some work and wait for that work to be finished, create a separate method that returns a Task, then await that.
Example:
Console.WriteLine("start")
await DoWorkAsync();
Console.WriteLine("end");
/////////
private Task DoWorkAsync()
{
return Task.Run(async () =>
{
await Task.Delay(3000);
});
}
Note that wrapping a method body into a Task and returning it, is not suggested, and it typically leads to a bit of a code smell.
Stephen Cleary has good information about Tasks and async/await. I would read up on this:
https://blog.stephencleary.com/2012/02/async-and-await.html
Will work like this, not that obvious though:
Func<Task> action = async () =>
{
await Task.Delay(3000);
};
Console.WriteLine("start");
await Task.Run(action);
Console.WriteLine("end");
You may try this:
Action action = async () =>
{
await Task.Delay(3000);
};
Console.WriteLine("start");
Task.Run(action).Wait();
Console.WriteLine("end");
await Task.WhenAll(a, b); continues albeit neither a nor b have completed (as they're in infinite loop)
public partial class App : Application, {
protected override async void OnStartup(StartupEventArgs e) {
var a = Task.Factory.StartNew(async () => {
while (true) {
Trace.WriteLine("A ->");
await Task.Delay(TimeSpan.FromSeconds(0.1));
Trace.WriteLine("-> A");
}
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
var b = Task.Factory.StartNew(async () => {
while (true) {
Trace.WriteLine("B ->");
await Task.Delay(TimeSpan.FromSeconds(0.09));
Trace.WriteLine("-> B");
}
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
await Task.WhenAll(a, b);
// I expected that the following line will never run, but it does:
base.OnStartup(e);
}
}
Why is that?
edit:
Apparently the editor/plugin/whatever misguided me here:
await Task.WhenAll(a, b); continues albeit neither a nor b have completed
But they have completed. That's exactly why WhenAll is completing as well. You can see this yourself by simply inspecting the status of the tasks at that point in time.
Since you're passing an async method to StartNew, it's going to return a Task<Task>. The outer task will be completed as soon as it starts the inner task. It will not wait to be completed until the inner task finishes. While you could unwrap the tasks and pass those inner tasks to WhenAll, you could just as easily not wrap the tasks in the first place as you're not accomplishing anything by doing so.
Just invoke the async lambdas yourself to create the tasks that you want.
public partial class App : Application
{
protected override async void OnStartup(StartupEventArgs e)
{
Func<Task> a = async () =>
{
while (true)
{
Trace.WriteLine("A ->");
await Task.Delay(TimeSpan.FromSeconds(0.1));
Trace.WriteLine("-> A");
}
};
Func<Task> b = async () =>
{
while (true)
{
Trace.WriteLine("B ->");
await Task.Delay(TimeSpan.FromSeconds(0.09));
Trace.WriteLine("-> B");
}
};
await Task.WhenAll(a(), b());
base.OnStartup(e);
}
}
Don't use Task.Factory.StartNew. Use Task.Run instead.
Task.Factory.StartNew pre-dates async-await so it doesn't expect an async delegate (i.e. Func<Task>). In that case it returns a Task<T> where T is itself a Task. So a and b aren't Tasks, they are Task<Task>. Task.Factory.StartNew here only starts a task that returns the actual task you want to wait for.
You can use Unwrap on a and b to return a task that represents the entire operation, meaning:
await Task.WhenAll(a.Unwrap(), b.Unwrap());
But, Task.Run is simpler and does that implicitly.
Imagine the following scenario :
public async Task DoMultipleWork() {
var uploadTask = UploadAsync(file);
var processingTask = Task.Run( () => DoCpuWork() );
await Task.WhenAll(uploadTask, processingTask);
Console.WriteLine("upload is done");
Console.WirteLine("processing is done");
}
How can I change that code so that it doesn't matter which one ends first, it execute some particular (sync or async) code.
So I fire the both task and when taskA or taskB ends, I just run some code (sync or async) independently of the other.
I think maybe ContinueWith but I'm not sure because it needs an another async method which is not really needed.
EDIT
As suggested by comments on answer, I want to clear that I want to execute different code depending on the task that completes, and get both Console.WriteLine executed as soon as the original task completes.
You want to use Task.WhenAny which returns the first task that completes. You can then tell which task completed by comparing to the original tasks. Before returning you should wait for the other one to complete explicitly (or wait for both with Task.WhenAll):
public async Task DoMultipleWork()
{
var uploadTask = UploadAsync(file);
var processingTask = Task.Run( () => DoCpuWork() );
var completedTask = await Task.WhenAny(uploadTask, processingTask);
Console.WriteLine("upload or processing is done");
if (completedTask == uploadTask)
{
// Upload completed
}
else
{
// Processing completed
}
await Task.WhenAll(uploadTask, processingTask) // Make sure both complete
Console.WriteLine("upload and processing are done");
}
As I describe on my blog, ContinueWith is dangerous unless you explicitly pass a scheduler. You should use await instead of ContinueWith in ~99% of cases (more detail in another blog post).
In your case:
private async Task UploadAsync(string filepath)
{
var result = await fileManager.UploadAsync(filepath);
Console.WriteLine($"Result from uploading file {result}");
}
private async Task ProcessAsync(string filepath, IProgress<T> progress)
{
await Task.Run(() => wordProcessor.Process(filepath, progress));
Console.WriteLine("processing completed");
}
...
await Task.WhenAll(UploadAsync(filepath), ProcessAsync(filepath, processingProgress));
public async Task DoMultipleWork() {
var uploadTask = UploadAsync(file);
var processingTask = Task.Run( () => DoCpuWork() );
uploadTask.ContinueWith((Task t) => Console.WriteLine("YOUR_MESSAGE"), TaskContinuationOptions.OnlyOnRanToCompletion);
processingTask.ContinueWith((Task t) => Console.WriteLine("YOUR_MESSAGE"), TaskContinuationOptions.OnlyOnRanToCompletion);
await Task.WhenAll(new []{uploadTask, processingTask});
}
I have long running processing that I want to perform in a background task. At the end of the task, I want to signal that it has completed. So essentially I have two async tasks that I want to run in the background, one after the other.
I am doing this with continuations, but the continuation is starting prior to the initial task completing. The expected behavior is that the continuation run only after the initial task has completed.
Here is some sample code that demonstrates the problem:
// Setup task and continuation
var task = new Task(async () =>
{
DebugLog("TASK Starting");
await Task.Delay(1000); // actual work here
DebugLog("TASK Finishing");
});
task.ContinueWith(async (x) =>
{
DebugLog("CONTINUATION Starting");
await Task.Delay(100); // actual work here
DebugLog("CONTINUATION Ending");
});
task.Start();
The DebugLog function:
static void DebugLog(string s, params object[] args)
{
string tmp = string.Format(s, args);
System.Diagnostics.Debug.WriteLine("{0}: {1}", DateTime.Now.ToString("HH:mm:ss.ffff"), tmp);
}
Expected Output:
TASK Starting
TASK Finishing
CONTINUATION Starting
CONTINUATION Ending
Actual Output:
TASK Starting
CONTINUATION Starting
CONTINUATION Ending
TASK Finishing
Again, my question is why is the continuation starting prior to the completion of the initial task? How do I get the continuation to run only after the completion of the first task?
Workaround #1
I can make the above code work as expected if I make the intial task synchronous - that is if I Wait on the Task.Delay like so:
var task = new Task(() =>
{
DebugLog("TASK Starting");
Task.Delay(1000).Wait(); // Wait instead of await
DebugLog("TASK Finishing");
});
For many reasons, it is bad to use Wait like this. One reason is that it blocks the thread, and this is something I want to avoid.
Workaround #2
If I take the task creation and move it into it's own function, that seems to work as well:
// START task and setup continuation
var task = Test1();
task.ContinueWith(async (x) =>
{
DebugLog("CONTINUATION Starting");
await Task.Delay(100); // actual work here
DebugLog("CONTINUATION Ending");
});
static public async Task Test1()
{
DebugLog("TASK Starting");
await Task.Delay(1000); // actual work here
DebugLog("TASK Finishing");
}
Credit for the above approach goes to this somewhat related (but not duplicate) question: Use an async callback with Task.ContinueWith
Workaround #2 is better than Workaround #1 and is likely the approach I'll take if there is no explanation for why my initial code above does not work.
Your original code is not working because the async lambda is being translated into an async void method underneath, which has no built-in way to notify any other code that it has completed. So, what you're seeing is the difference between async void and async Task. This is one of the reasons that you should avoid async void.
That said, if it's possible to do with your code, use Task.Run instead of the Task constructor and Start; and use await rather than ContinueWith:
var task = Task.Run(async () =>
{
DebugLog("TASK Starting");
await Task.Delay(1000); // actual work here
DebugLog("TASK Finishing");
});
await task;
DebugLog("CONTINUATION Starting");
await Task.Delay(100); // actual work here
DebugLog("CONTINUATION Ending");
Task.Run and await work more naturally with async code.
You shouldn't be using the Task constructor directly to start tasks, especially when starting async tasks. If you want to offload work to be executed in the background use Task.Run instead:
var task = Task.Run(async () =>
{
DebugLog("TASK Starting");
await Task.Delay(1000); // actual work here
DebugLog("TASK Finishing");
});
About the continuation, it would be better to just append it's logic to the end of the lambda expression. But if you're adamant on using ContinueWith you need to use Unwrap to get the actual async task and store the it so you could handle exceptions:
task = task.ContinueWith(async (x) =>
{
DebugLog("CONTINUATION Starting");
await Task.Delay(100); // actual work here
DebugLog("CONTINUATION Ending");
}).Unwrap();
try
{
await task;
}
catch
{
// handle exceptions
}
Change your code to
// Setup task and continuation
var t1 = new Task(() =>
{
Console.WriteLine("TASK Starting");
Task.Delay(1000).Wait(); // actual work here
Console.WriteLine("TASK Finishing");
});
var t2 = t1.ContinueWith((x) =>
{
Console.WriteLine("C1");
Task.Delay(100).Wait(); // actual work here
Console.WriteLine("C2");
});
t1.Start();
// Exception will be swallow without the line below
await Task.WhenAll(t1, t2);
public class PerformMainTask()
{
Task1();
Task2();
PerformLongTask();
Task3();
Task4();
}
What I would like to achieve here is to PerformLongTask() onto another thread, and to continue with Task3 & Task4 even when PerformLongTask() is still running.
How should my PerformLongTask() be like in a C# 5.0 way?
Do I need to use async/await?
The simplest solution I know of is:
Task1();
Task2();
var task3 = Task.Run(() => PerformLongTask());
Task4();
Task5();
task3.Wait(); //if task3 has not started yet it will be inlined here
Simple and efficient. If you need to propagate errors you should probably use Parallel.Invoke:
Parallel.Invoke(
() => { PerformLongTask(); },
() => { Task4(); Task5(); }
);
Assuming you are using C# 5 and all your Task() methods truly return a Task (or anything awaitable), your code should look like that:
public async Task PerformMainTask()
{
await Task1();
await Task2();
// Start long task
var longTask = PerformLongTask();
await Task3();
await Task4();
//wait for long task to finish
await longTask;
}
However, if your long task does not run parallelly on its own, you can force it to do so with Task.Run:
public async Task PerformMainTask()
{
await Task1();
await Task2();
// Start long task
var longTask = Task.Run(PerformLongTask);
await Task3();
await Task4();
//wait for long task to finish
await longTask;
}
If none are your tasks are really tasks, just strip all the await except the last one, and you will be good to go.
public class PerformMainTask()
{
Task1();
Task2();
Task.WaitAll(Task.Factory.StartNew(() => PerformLongTask()), Task.Factory.StartNew(() => { Task3(); Task4(); }));
}