Making interface implementations async

前端 未结 3 1136
太阳男子
太阳男子 2020-12-23 02:26

I’m currently trying to make my application using some Async methods. All my IO is done through explicit implementations of an interface and I am a bit confused about how to

3条回答
  •  醉话见心
    2020-12-23 03:10

    Better solution is to introduce another interface for async operations. New interface must inherit from original interface.

    Example:

    interface IIO
    {
        void DoOperation();
    }
    
    interface IIOAsync : IIO
    {
        Task DoOperationAsync();
    }
    
    
    class ClsAsync : IIOAsync
    {
        public void DoOperation()
        {
            DoOperationAsync().GetAwaiter().GetResult();
        }
    
        public async Task DoOperationAsync()
        {
            //just an async code demo
            await Task.Delay(1000);
        }
    }
    
    
    class Program
    {
        static void Main(string[] args)
        {
            IIOAsync asAsync = new ClsAsync();
            IIO asSync = asAsync;
    
            Console.WriteLine(DateTime.Now.Second);
    
            asAsync.DoOperation();
            Console.WriteLine("After call to sync func using Async iface: {0}", 
                DateTime.Now.Second);
    
            asAsync.DoOperationAsync().GetAwaiter().GetResult();
            Console.WriteLine("After call to async func using Async iface: {0}", 
                DateTime.Now.Second);
    
            asSync.DoOperation();
            Console.WriteLine("After call to sync func using Sync iface: {0}", 
                DateTime.Now.Second);
    
            Console.ReadKey(true);
        }
    }
    

    P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.

提交回复
热议问题