In my code I assume that outerFlag will be hit after innerFlag but it actually runs like fire and forget (innerFlag is hit after outerFlag). When I use Thread.Sleep instead of Task.Delay flags are hit in correct order.
Here is the code:
[Test]
public async Task Test() {
bool innerFlag = false;
bool outerFlag = false;
await Lock(async () => {
await Task.Delay(2000);
innerFlag = true;
});
outerFlag = true;
Thread.Sleep(1000);
Thread.Sleep(2500);
}
private Task Lock(Action action) {
return Task.Run(action);
}
I also noticed that when I call Task.Delay and set innerFlag without a Lock method but by direct lambda, it works as expected.
Can somebody explain such behaviour?
Your Lock method doesn't understand async delegates, so the async delegate you are trying to pass as argument is treated as async void. Async voids are problematic in all sorts of ways and should be avoided, unless they are used for their intended purpose, as event handlers.
To ensure that your method understand async delegates you must create an overload that accepts a Func<Task> as argument:
private Task Lock(Func<Task> func)
{
return Task.Run(func);
}
Notice that the func argument can be passed directly to Task.Run, because this method understands async delegates too. Not all built-in methods understand async delegates, with notable examples the Task.Factory.StartNew and Parallel.ForEach. You must be cautious every time you add the async modifier in a delegate. You must be sure that the called method understands async delegates, or else you may end up with async voids and the havoc they create.
Related
How can I wait for a void async method to finish its job?
for example, I have a function like below:
async void LoadBlahBlah()
{
await blah();
...
}
now I want to make sure that everything has been loaded before continuing somewhere else.
Best practice is to mark function async void only if it is fire and forget method, if you want to await on, you should mark it as async Task.
In case if you still want to await, then wrap it like so await Task.Run(() => blah())
If you can change the signature of your function to async Task then you can use the code presented here
The best solution is to use async Task. You should avoid async void for several reasons, one of which is composability.
If the method cannot be made to return Task (e.g., it's an event handler), then you can use SemaphoreSlim to have the method signal when it is about to exit. Consider doing this in a finally block.
You don't really need to do anything manually, await keyword pauses the function execution until blah() returns.
private async void SomeFunction()
{
var x = await LoadBlahBlah(); <- Function is not paused
//rest of the code get's executed even if LoadBlahBlah() is still executing
}
private async Task<T> LoadBlahBlah()
{
await DoStuff(); <- function is paused
await DoMoreStuff();
}
T is type of object blah() returns
You can't really await a void function so LoadBlahBlah() cannot be void
I know this is an old question, but this is still a problem I keep walking into, and yet there is still no clear solution to do this correctly when using async/await in an async void signature method.
However, I noticed that .Wait() is working properly inside the void method.
and since async void and void have the same signature, you might need to do the following.
void LoadBlahBlah()
{
blah().Wait(); //this blocks
}
Confusingly enough async/await does not block on the next code.
async void LoadBlahBlah()
{
await blah(); //this does not block
}
When you decompile your code, my guess is that async void creates an internal Task (just like async Task), but since the signature does not support to return that internal Tasks
this means that internally the async void method will still be able to "await" internally async methods. but externally unable to know when the internal Task is complete.
So my conclusion is that async void is working as intended, and if you need feedback from the internal Task, then you need to use the async Task signature instead.
hopefully my rambling makes sense to anybody also looking for answers.
Edit:
I made some example code and decompiled it to see what is actually going on.
static async void Test()
{
await Task.Delay(5000);
}
static async Task TestAsync()
{
await Task.Delay(5000);
}
Turns into (edit: I know that the body code is not here but in the statemachines, but the statemachines was basically identical, so I didn't bother adding them)
private static void Test()
{
<Test>d__1 stateMachine = new <Test>d__1();
stateMachine.<>t__builder = AsyncVoidMethodBuilder.Create();
stateMachine.<>1__state = -1;
AsyncVoidMethodBuilder <>t__builder = stateMachine.<>t__builder;
<>t__builder.Start(ref stateMachine);
}
private static Task TestAsync()
{
<TestAsync>d__2 stateMachine = new <TestAsync>d__2();
stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
stateMachine.<>1__state = -1;
AsyncTaskMethodBuilder <>t__builder = stateMachine.<>t__builder;
<>t__builder.Start(ref stateMachine);
return stateMachine.<>t__builder.Task;
}
neither AsyncVoidMethodBuilder or AsyncTaskMethodBuilder actually have any code in the Start method that would hint of them to block, and would always run asynchronously after they are started.
meaning without the returning Task, there would be no way to check if it is complete.
as expected, it only starts the Task running async, and then it continues in the code.
and the async Task, first it starts the Task, and then it returns it.
so I guess my answer would be to never use async void, if you need to know when the task is done, that is what async Task is for.
do a AutoResetEvent, call the function then wait on AutoResetEvent and then set it inside async void when you know it is done.
You can also wait on a Task that returns from your void async
You can simply change the return type to Task and call await Task.CompletedTask at the end of the function, e.g:
async Task MyFunction() {
await AnotherFunction();
await Task.CompletedTask;
}
I find this simpler than wrapping the whole function body in a call to Task.Run(() => { ... });.
I've read all the solutions of the thread and it's really complicated... The easiest solution is to return something like a bool:
async bool LoadBlahBlah()
{
await blah();
return true;
}
It's not mandatory to store or chekc the return value. You can juste do:
await LoadBlahBlah();
... and you can return false if something goes wrong.
The System.Diagnostics.ConditionalAttribute is really useful for sectioning off pieces of Debug code without needing to use compiler directives but it is only compatible with methods that return void.
Is there a way to use it (or something equivalent) for async methods that return a Task?
No.
A void method can be removed without any problem because the net effect on the evaluation stack is the same whether there is a method call there or not: zero.
A non-void method cannot be removed because in the case where it is removed, there are zero things on the stack, and in the case where it is not removed, there is one thing on the stack: a reference to a task.
Put another way: what would you expect this to do:
Foo(BarAsync());
if Foo takes a Task and BarAsync is removed?
Is there a way to use it (or something equivalent) for async methods that return a Task?
Same as with any value-returning function: wrap the call in a helper method returning void, "returning" the value through a ref parameter. Yes, it's clumsy, but this way you're forced to write an initialiser for the return parameter, and that initialiser is how it can be valid even if the call is removed: you can never end up with uninitialised values.
[Conditional("DEBUG")]
public void FooAsync(ref Task task) {
Func<Task> impl = async () => {
// ...
};
task = impl();
}
Usage:
public async Task CallFoo() {
var task = Task.CompletedTask;
FooAsync(ref task);
await task;
}
I've searched for the answer to this but according to many guides and SO questions this code still appears correct to me, yet it runs synchronously.
private void CheckConditions()
{
foreach (var obj in myObjects)
{
if (obj.ConditionMet)
{
HandleConditionAsync(obj);
}
}
DoOtherWork();
}
private async void HandleConditionAsync(MyObject obj)
{
// shouldn't control transfer back to CheckConditions() here while we wait for user input?
string userInput = await obj.MessagePromptAsync("hello user");
DoSomeBookkeeping(obj);
}
// (MyObject.cs)
private MessagePrompt messagePrompt; // inherits from UserControl
public async Task<string> MessagePromptAsync(string prompt)
{
return await Task.FromResult<string>(messagePrompt.Prompt(prompt));
}
// (MessagePrompt.cs)
public string Prompt(string prompt)
{
this.UIThread(() => this.SetMessagePrompt(prompt));
userInputAutoResetEvent.WaitOne();
return myResult; // set in a button handler that also sets the AutoResetEvent
}
I'm intending for CheckConditions() to continue along merrily but instead it is stuck on MessagePrompt's AutoResetEvent despite my async/awaits. The only thing I can figure might be wrong is that perhaps MessagePrompt's methods aren't able to run asynchronously due to some restriction from UserControl, its use of a UI thread reference, or maybe non-async methods at the top of the stack.
There's nothing in your code that's asynchronous. The only task you have, you created from a result value, meaning the Prompt() method has to complete and return its result before you'll even get the Task object back to wait on. That object will already be completed, so any await on it will complete immediately, once it has the Task to wait on.
Maybe you meant this instead:
public async Task<string> MessagePromptAsync(string prompt)
{
return await Task.Run(() => messagePrompt.Prompt(prompt));
}
Or alternatively (if you really do have nothing else in the MessagePromptAsync() method):
public Task<string> MessagePromptAsync(string prompt)
{
return Task.Run(() => messagePrompt.Prompt(prompt));
}
Note that this may lead to a different problem, depending on what DoOtherWork() and UIThread() actually do. If your UI thread gets tied up in DoOtherWork() and the UIThread() method is wrapping Dispatcher.Invoke() or similar, then you'll have a deadlock.
If that does not address your problem, please provide a good Minimal, Complete, and Verifiable code example that reliably reproduces the problem.
You need to make CheckConditions() async as well, and then await the call to HandleConditionAsync(MyObject obj). CheckConditions() runs synchronously in your sample.
private async Task CheckConditionsAsync()
{
foreach (var obj in myObjects)
{
if (obj.ConditionMet)
{
await HandleConditionAsync(obj);
}
}
DoOtherWork();
}
Also, and this is just a best practices thing, an async method should always return a Task when possible. The only time I've ever had to use async void is for compatibility with an event handler. You can see I've changed CheckConditions() this way, and HandleConditionAsync(MyObject obj) should be modified similarly. I also changed the method name to represent it's asynchronous behaviour.
If you need to run a method that returns a Task synchronously (and you shouldn't do this, this is an indication of something incorrect about your design), you can run it with Task.FromResult(MyMethodAsync()). Again, avoid doing this wherever you can, it defeats the purpose of making a method asynchronous to in the first place.
For example, in the code below, the last method M2Async is synchronous and does not have async/await as otherwise there would need to be a call to M3Async after await and the call graph would continue?
For clarity (from C# in a Nutshell):
A synchronous operation does its work before returning to the caller.
An asynchronous operation does (most or all of) its work after returning to the caller.
public void Main()
{
Task task = M1Async();
// some work
int i = task.result;
// use i etc
}
private async Task M1Async()
{
int i = await M2Async();
// some work
return i;
}
private Task M2Async()
{
return Task.FromResult(2);
}
That depends a bit on what you mean by "synchronous". In some ways, all methods are synchronous (even async ones) - they just synchronously return something that can be awaited and which might have more things to do once awaited.
No, it doesn't have to be synchronous; your code could just as well be:
private async Task<int> M2Async()
{
return await Task.FromResult(2);
}
or even just (although the compiler will detect that this is a smell, and is secretly synchronous):
private async Task<int> M2Async()
{
return 2;
}
Neither of which would be particularly useful, but; they would work. In reality, most async methods will bottom out at something that is doing async IO - file-system, network, etc. In your example, there is nothing that will actually truly be async anyway - it will all be completed when the await is reached.
in my Method RecalcChartAsync i do some time intensive stuff.. so i thought i'll do some things async.
I want to start the two Methods CreateHistogramAsync CalculatePropValuesAsync and in the meanwhile do some stuff in my RecalcChartsAsync and finally wait for it to complete.
private async void RecalcChartsAsync()
{
var histogram = CreateHistogramAsync();
var propValues = CalculatePropValuesAsync();
//do some other stuff
await histogram;
await propValues;
}
private async Task CreateHistogramAsync()
{
//do some stuff
}
private async Task CalculatePropValuesAsync()
{
//do some stuff
}
Im not sure if i am doing it the right way because ReSharper gives me the following warning at the async Keyword at CreateHistogramAsync and CalculatePropValueAsync:
This async method lacks 'await' operators and will run synchronously. Consider using the await operator to await non-blocking API calls, ...
Now i am not sure if i am using this async thing in the correct way.
Now i am not sure if i am using this async thing in the correct way.
It doesn't sound like it. Just because you have an async method doesn't mean it's going to run on a separate thread - and it sounds like that's what you're expecting. When you execute an async method, it will run synchronously - i.e. just like normal - until it hits the first await expression. If you don't have any await expressions, that means it will just run as normal, the only difference being the way that it's wrapped up in a state machine, with the completion status (exceptions etc) represented by a task.
I suspect you should change your CreateHistogramAsync and CalculatePropValuesAsync methods to be just synchronous:
private void CreateHistogram()
{
...
}
private void CalculatePropValues()
{
...
}
and use Task.Run to execute them in parallel:
private async void RecalcChartsAsync()
{
var histogram = Task.Run((Action) CreateHistogram);
var propValues = Task.Run((Action) CalculatePropValues);
//do some other stuff
await histogram;
await propValues;
}
There is nothing you're awaiting on within your methods, so marking then as async is pointless. That's why ReSharper is warning you.
You should start from learning how async/await works: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx
If you are not awaiting anything in your two last methods, then remove the async from the declaration. In this case, creating and returning the task will be enough to achieve what you want.