1

I think I'm missing something but I cant seem to get await to work in .net 4.5

Does anyone know the correct syntax here? everywhere I've looked seems to use exactly what I've got. (see Proper use of Task.Delay to delay key presses)

enter image description here

Community
  • 1
  • 1
undefined
  • 33,537
  • 22
  • 129
  • 198
  • 2
    Could you post the relevant parts of your code? Did you actually read the error message? – svick Sep 07 '12 at 01:14
  • as much as svick's comment might be considered a little harsh, he *does* have a good point - the compiler team put in an excellent error message here, telling exactly how to fix the problem. :) – James Manning Sep 07 '12 at 03:24

2 Answers2

4

It looks like you're trying to invoke an asynchronous method from a lambda. You're probably missing the async at the start. For example"

SomeMethod(async () =>
    {
        //...
        await Task.Delay(1000, cancellationToken);
    });
Peter Ritchie
  • 35,463
  • 9
  • 80
  • 98
  • 2
    You should avoid using `void`-returning `async` methods (or lamdas) if possible. They make error handling more difficult. – svick Sep 07 '12 at 01:15
  • 1
    just to make it explicit for others that run across this, you can just change the type of the local var from Action to Func in order to resolve svick's concern. This isn't a comment directed at you two, just trying to help others that may not 'get' how they would change the code so they could get a Task out of it. :) – James Manning Sep 07 '12 at 03:22
  • I assumed he was calling a method that took a delegate and only needed the `async` so that he could call await on `Task.Delay`. I've updated the answer to reflect that. – Peter Ritchie Sep 07 '12 at 03:39
2

You need to put async on your method...the one that encloses your block of code.

Community
  • 1
  • 1
Colin Smith
  • 12,375
  • 4
  • 39
  • 47