在基类上有虚拟异步方法可以吗? [英] Is it OK to have virtual async method on base class?

查看:76
本文介绍了在基类上有虚拟异步方法可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一些代码,其中我有2个类,它们的逻辑和代码非常相似.我在两个类上都有protected async void LoadDataAsync()方法.
目前,我正在对其进行重构,并正在考虑将共享逻辑移至基类.
在基类上具有virtual async方法并在派生类上重写它是否可以?
有什么问题吗?
我的代码如下:

I am working with some code, where I have 2 classes with very similar logic and code. I have protected async void LoadDataAsync() method on both classes.
Currently I am refactoring it and thinking to move shared logic to base class.
Is it OK to have virtual async method on base class and override it on derived classes?
Are there any issues with it?
My code looks like this:

public class Base
{
   protected virtual async void LoadDataAsync() {}
}

public class Derived : Base
{
   protected override async void LoadDataAsync()
   {
       // awaiting something
   }
}

类似(但不相同)问题已经被提出.

推荐答案

简短答案

  • 可以将virtual方法 标记为async
  • 不能将abstract方法 标记为async
  • Short answer

    • A virtual method may be marked as async
    • An abstract method cannot be marked as async
    • 其原因是async实际上不是方法签名的一部分.它只是告诉编译器如何处理方法主体本身的编译(不适用于覆盖方法).由于抽象方法没有方法主体,因此应用async修饰符没有任何意义.

      The reason for this is async is not actually part of the method signature. It simply tells the compiler how to handle the compilation of the method body itself (and does not apply to overriding methods). Since an abstract method does not have a method body, it does not make sense to apply the async modifier.

      如果基类提供了该方法的默认实现但不需要执行任何工作,那么我建议您使用以下方法,而不是基类中的当前签名:

      Rather than your current signature in the base class, I would recommend the following if the base class provides a default implementation of the method but does not need to do any work.

      protected virtual Task LoadDataAsync() {
        return Task.FromResult(default(object));
      }
      

      实施中的主要变化如下:

      The key changes from your implementation are the following:

      1. 将返回值从void更改为Task(请记住,async实际上不是返回类型的一部分).与返回void不同,返回Task时,调用代码可以执行以下任一操作:
        • 等待操作完成
        • 检查任务状态(完成,取消,故障)
      1. Change the return value from void to Task (remember async is not actually part of the return type). Unlike returning void, when a Task is returned calling code has the ability to do any of the following:
        • Wait for the operation to complete
        • Check the status of the task (completed, canceled, faulted)

      这篇关于在基类上有虚拟异步方法可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆