简体   繁体   English

覆盖非异步方法时如何正确调用C#异步方法?

[英]How to properly call a C# async method when overriding an non-async method?

I am creating a TagHelper for a RazorPage. 我正在为RazorPage创建TagHelper。 The TagHelper class's only requirement is that the process method get overridden. TagHelper类的唯一要求是覆盖处理方法。

Here is the signature (and thank you for the solution Stephen let's just assume that ProcessAsync doesn't exist so we can still answer the question). 这是签名(感谢您的解决方案,斯蒂芬让我们假设ProcessAsync不存在,所以我们仍然可以回答问题)。

public override void Process(TagHelperContext context, TagHelperOutput output)

The body is very simple 身体很简单

if(_roleService.CanRegisterAsync().Result)
{
    output.SuppressOutput();
}

I hear that deadlocks can be caused by calling .Result on async methods so I don't want to call it as written above because it seems like I could run into some trouble. 我听说死锁可能是由在异步方法上调用.Result引起的,所以我不想像上面写的那样调用它,因为看来我可能会遇到一些麻烦。

So, I change the virtual override by adding async to 因此,我通过添加异步来更改虚拟覆盖

public override async void Process(TagHelperContext context, TagHelperOutput output)

and the body to 和身体

if(await _roleService.CanRegisterAsync())
{
    output.SuppressOutput();
}

This compiles fine but the output.SupressOutput() doesn't to seem to have any effect anymore so I am forced to go back to the original code which seems like a bad idea. 这样编译就可以了,但是output.SupressOutput()似乎不再起作用了,所以我不得不回到原始代码,这似乎是个坏主意。

Is there any better way to deal with this situation so I don't potentially run into deadlocks as many people talk about in other async posts? 有什么更好的方法来处理这种情况,这样我就不会像其他人在其他异步帖子中所说的那样陷入僵局?

You need to create an asynchronous tag helper ; 您需要创建一个异步标签助手 in other words, override ProcessAsync instead of Process . 换句话说,重写ProcessAsync而不是Process That way you can use await : 这样,您可以使用await

public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
  if(await _roleService.CanRegisterAsync())
  {
    output.SuppressOutput();
  }
  ...
}

Apparently what you are after is the following: 显然,您追求的是以下内容:

if(_roleService.CanRegisterAsync().WaitAndUnwrapException())
{
    output.SuppressOutput();
}

Remark : The name of the method strongly suggests using a try/catch to handle possible exceptions 备注 :该方法的名称强烈建议使用try/catch处理可能的异常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM