35

Consider Using async without await.

think that maybe you misunderstand what async does. The warning is exactly right: if you mark your method async but don't use await anywhere, then your method won't be asynchronous. If you call it, all the code inside the method will execute synchronously.

I want write a method that should run async but don't need use await.for example when use a thread

public async Task PushCallAsync(CallNotificationInfo callNotificationInfo)
{
    Logger.LogInfo("Pushing new call {0} with {1} id".Fill(callNotificationInfo.CallerId,
}

I want call PushCallAsync and run async and don't want use await.

Can I use async without await in C#?

Rand Random
  • 6,633
  • 10
  • 37
  • 81
  • @J.Steen so if use this run async? –  Jul 23 '13 at 09:15
  • 2
    Well. It's all up to what your design issue is, here. What do you expect "async" to do? – J. Steen Jul 23 '13 at 09:15
  • Without `await` your method will execute `Synchronously` – Sriram Sakthivel Jul 23 '13 at 09:16
  • @J.Steen i want run in other thread –  Jul 23 '13 at 09:17
  • 6
    If you're not going to await this method why bother declaring it async at all? The text that you quote sums it up pretty nicely IMO. – BoltClock Jul 23 '13 at 09:17
  • Run in other thread. Sure. Do you want to wait for it to finish? Or just fire-and-forget? From the content, looks like just a fire-and-forget. – J. Steen Jul 23 '13 at 09:18
  • 1
    I think you just use [`Task.Run`](http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.run.aspx) directly. `async`/`await` isn't really a multithreading mechanism, in fact I think the runtime executes things on as few threads as possible. It's mostly about the compiler automatically transform your code into continuation-passing style so you only *wait for results* (or completion) of a background operation when absolutely necessary. When you don't need to wait (or `await`) for the results of your call, this is not the language feature you're looking for. – millimoose Jul 23 '13 at 09:28
  • See also what the docs have to say about this: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx#BKMK_Threads (I was wrong, there's just a *single* thread and nonblocking IO involved. – millimoose Jul 23 '13 at 09:38
  • 3
    @millimoose: The way `async` interacts with threads is a bit more complex, and the default behavior can be easily overridden. `async` is not a multithreading mechanism, nor does it always run on a single thread. [I have a blog post that summarizes how `async` schedules its continuations](http://blog.stephencleary.com/2012/02/async-and-await.html). – Stephen Cleary Jul 23 '13 at 15:41
  • @StephenCleary So it'd be fairer to say that (as far as the OP needs to be concerned) an `async` method achieves asynchronicity using some mechanism appropriate to the use case, and that this mechanism can be considered an implementation detail? And that from this follows that merely declaring a method as `async` does not in fact introduce asynchronicity, and the keyword serves only to trigger the compiler rewrites from sequential style to CPS. – millimoose Jul 23 '13 at 18:53
  • 1
    @millimoose: Not an implementation detail. It is clearly specified - and has to be, so its behavior is always predictable and reliable (once you understand the mechanism). – Stephen Cleary Jul 23 '13 at 18:58

4 Answers4

34

If your Logger.LogInfo is already async this is enough:

public void PushCallAsync(CallNotificationInfo callNotificationInfo)
{
    Logger.LogInfo("Pushing new call {0} with {1} id".Fill(callNotificationInfo.CallerId,
}

If it is not just start it async without waiting for it

public void PushCallAsync(CallNotificationInfo callNotificationInfo)
{
    Task.Run(() => Logger.LogInfo("Pushing new call {0} with {1} id".Fill(callNotificationInfo.CallerId));
}
Moerwald
  • 9,219
  • 7
  • 35
  • 71
Visions
  • 901
  • 1
  • 7
  • 17
  • I read it, seems to me more like a style difference than an actual difference in bahavior, isn't it? – Visions Jul 24 '13 at 07:10
  • 10
    No. `Task.Run` uses different defaults: `DenyChildAttach` and `TaskScheduler.Default`. The `TaskScheduler` is particularly important because `StartNew` will use `TaskScheduler.Current` by default, which makes it schedule the delegate differently based on the context of the caller. This has tripped up so many people that many teams have adopted code rules that never allow `StartNew` unless the `TaskScheduler` is specified. – Stephen Cleary Jul 24 '13 at 11:03
  • Didn't know that, thx for the info. Changed the code to Task.Run – Visions Jul 25 '13 at 07:47
  • 7
    By convention you should not name a method "Async" unless it has the "async" keyword. – Graeme Wicksted Nov 08 '16 at 14:36
33

You still are misunderstanding async. The async keyword does not mean "run on another thread".

To push some code onto another thread, you need to do it explicitly, e.g., Task.Run:

await Task.Run(() => Logger.LogInfo("Pushing new call {0} with {1} id".Fill(callNotificationInfo.CallerId));

I have an async/await intro post that you may find helpful.

Stephen Cleary
  • 406,130
  • 70
  • 637
  • 767
6

You're misunderstanding async. It actually just tells the Compiler to propagate the inversion of control flow it does in the background for you. So that the whole method stack is marked as async.

What you actually want to do depends on your problem. (Let's consider your call Logger.LogInfo(..) is an async method as it does eventually call File.WriteAsync() or so.

  • If you calling function is a void event handler, you're good. The async call will happen to some degree (namely File.WriteAsync) in the background. You do not expect any result in your control flow. That is fire and forget.
  • If however you want to do anything with the result or if you want to continue only then, when Logger.LogInfo(..) is done, you have to do precautions. This is the case when your method is somehow in the middle of the call-stack. Then Logger.LogInfo(..) will usually return a Task and that you can wait on. But beware of calling task.Wait() because it will dead lock your GUI-Thread. Instead use await or return the Task (then you can omit async):

public void PushCallAsync(CallNotificationInfo callNotificationInfo) 
{
   return Logger.LogInfo("Pushing new call {0} with {1} id".Fill(callNotificationInfo.CallerId); 
}

or

 public async void PushCallAsync(CallNotificationInfo callNotificationInfo) 
 {
    await Logger.LogInfo("Pushing new call {0} with {1} id".Fill(callNotificationInfo.CallerId); 
 }
Orkhan Alikhanov
  • 7,611
  • 3
  • 36
  • 51
Robetto
  • 719
  • 7
  • 20
  • 5
    You should not use `async void` unless it is an event handler. That is the only acceptable time and is the only correct way of making an async event handler. If your synchronous method is `void`, it should be `async Task`. This is due to exception handling where event handlers will throw on the `SynchronizationContext` (similarly to synchronous events) rather than the caller. If possible the async event handler should be a thin private wrapper an `async Task` function (so it can be tested or re-used). – Graeme Wicksted Nov 08 '16 at 14:45
  • @GraemeWicksted you are certainly right and I support 'do not do async void' but for the understanding it is what I need - and eventually you'll usually have async void somewhere – Robetto Aug 15 '19 at 09:09
  • I'm not sure I understand your reply. How is it justified here? Looks like it should be `async Task` to me as it is not an event handler. Remember: `async Task` is essentially `async Task` but the latter simply does not exist. The only difference between `async void` and `async Task` is exception propagation and it only makes sense on event handlers. I have not observed a concrete example that would indicate otherwise. – Graeme Wicksted Aug 16 '19 at 14:46
2

If Logger.LogInfo is a synchronous method, the whole call will be synchronous anyway. If all you want to do is to execute the code in a separate thread, async is not the tool for the job. Try with thread pool instead:

ThreadPool.QueueUserWorkItem( foo => PushCallAsync(callNotificationInfo) );
ya23
  • 13,952
  • 9
  • 44
  • 42
  • 1
    Favour the Parallel Task library, rather than calling the threadpool directly... this can have rather unforeseen consequences depending on the platform (WinRT, Win, WP8, etc). In my experience. =) – J. Steen Jul 23 '13 at 09:23
  • 2
    You got me interested... Could you please provide more details on what the consequences could be? – ya23 Jul 23 '13 at 09:27
  • Well. I've managed to completely choke the CPU on several devices, using `QueueUserWorkItem` (using only two threads, mind you, so it's touchy as well), whereas the Task library will manage it perfectly. I've also had an issue where I've queued several threads, and none reaches the callback until they're all done, in a sort of thread-avalanche. – J. Steen Jul 23 '13 at 09:30
  • 1
    Consider [this question and its answers, and further reading](http://stackoverflow.com/questions/9200573/threadpool-queueuserworkitem-vs-task-factory-startnew). – J. Steen Jul 23 '13 at 09:38
  • 2
    *If Logger.LogInfo is not a synchronous method* don't you mnean If *Logger.LogInfo **is** a synchronous method*?? – Liam Jul 08 '16 at 14:26