33

I'd like to make a function async, so I simply add async like this:

public async static void something(){
}

You can see that its return-type is void. I just want this function to be called asynchronously without blocking, since return is void so no await is needed.

But Visual Studio 2012 just cannot compile this, it says that I miss await?

Could you please advise a sample that makes a function async without using await.


1 답변


30

I 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.

Also, you should try to avoid using async void methods, they make handling exceptions difficult.


  • async make the method itself asynchronous or not when the method get called, if no await anywhere inside the method? As above sample, if I call something(), will it block current thread? - Eric Yin
  • Yes, if you have some long-running code inside something() (and no await), then it will block the thread. That's what the warning is trying to tell you. - svick
  • async is not something that will make your methods magically not block. If you want to run some code on another thread, use Task.Run(). - svick
  • Ohh, got it, I misunderstand the concert, async mark the method is going to use async call not mean itself is async. - Eric Yin
  • @Patrick Then you can use Task.Run() to run it on another thread. - svick

Linked


Related

Latest