0

I have base class and creating virtual stubs for usage by subscribers. I just migrated to async/await pattern and having trouble getting it right with tasks.

Here is how I want it to be in base class:

public virtual Task<bool> OnBeforeSaveAsync()
{
    return new Task<bool>(p => true);
}

Basically if implementing class doesn't have override - I want this function complete and return "True"

How should I code it?

katit
  • 17,375
  • 35
  • 128
  • 256
  • are you missing the async identifier? public virtual async Task – Machinegon Mar 12 '13 at 19:30
  • @Machinegon: The `async` modifier is not needed if the `await` keyword isn't used in the method body. – dtb Mar 12 '13 at 19:30
  • @dtb Didn't knew about that, ty! – Machinegon Mar 12 '13 at 19:32
  • You could make the method `async` then simply return `true`. For example `public virtual async Task Method() { return true; }` then any overriding methods could actually start a new Task, if needed. – Peter Ritchie Mar 12 '13 at 19:47
  • Peter, tried this - resharper complains that I use async without await. Which still works, I just wasn't sure if it is correct way of doing it – katit Mar 12 '13 at 20:33
  • 1
    Yeah, if you're doing the `virtual` thing, that's fine. It's a warning; but if the expected usage is to override the method and use `await` *then* it's safe to ignore. You'll also get a CS1998 compiler warning--it's just telling you that you've got the overhead of the async state machine without actually making use of it. You could go the return new Task route; but then you've got an `override` that looks different (has `async`, but the `virtual` doesn't) which could be confusing to some people--but is about 160% slower – Peter Ritchie Mar 12 '13 at 21:07
  • It's not required override, only ~20% of implementations override those stubs. What do you mean by "slower". New task slower or making virtual async slower? – katit Mar 12 '13 at 21:19
  • 1
    @katit `async` is slower than not using `async` and returning a completed task. – Peter Ritchie Mar 12 '13 at 21:23

0 Answers0