Suppress warning CS1998: This async method lacks 'await'

前端 未结 14 996
遇见更好的自我
遇见更好的自我 2020-11-28 04:21

I\'ve got an interface with some async functions. Some of the classes that implements the interface does not have anything to await, and some might just throw. It\'s a b

14条回答
  •  佛祖请我去吃肉
    2020-11-28 05:06

    I know this is an old thread, and perhaps this won't have the right effect for all usages, but the following is as close as I can get to being able to simply throw a NotImplementedException when I haven't yet implemented a method, without altering the method signature. If it's problematic I'd be happy to know about it, but it barely matters to me: I only use this while in development anyway, so how it performs isn't all that important. Still, I'd be happy to hear about why it's a bad idea, if it is.

    public async Task test()
    {
        throw await new AwaitableNotImplementedException();
    }
    
    
    

    Here's the type I added to make that possible.

    public class AwaitableNotImplementedException : NotImplementedException
    {
        public AwaitableNotImplementedException() { }
    
        public AwaitableNotImplementedException(string message) : base(message) { }
    
        // This method makes the constructor awaitable.
        public TaskAwaiter> GetAwaiter()
        {
            throw this;
        }
    }
    

    提交回复
    热议问题