我有最新的MediatR(12.2.0),并且我有一个不返回任何内容的同步方法.我真的需要使用"异步任务"而不是"任务"吗?因为下面的方法给了我"并非所有代码路径都返回值":

public class UploadFileCommandHandler(IFileUploadingService fileUploadingService) 
    : IRequestHandler<UploadFileCommand>
{
    private readonly IFileUploadingService _fileUploadingService = fileUploadingService;

    public /* async */ Task Handle(UploadFileCommand request, CancellationToken cancellationToken)
    {
        _fileUploadingService.UploadFile(request.File); // <- this method returns VOID, not a task, see it below (the interface IFileUploadingService)
    }
}

public interface IFileUploadingService
{
    void UploadFile(File file);
}

我不得不添加"bloc",但我有警告"bloc方法缺乏等待".什么是正确的解决方案?

推荐答案

根据这个名字,理想情况下你应该将IFileUploadingService.UploadFile重构为IFileUploadingService.UploadFile c("真正的"IFileUploadingService.UploadFile c),因为它看起来是IO-bound operation.

如果接口/实现不在您的控制范围之内,则通常的方法是返回Task.CompletedTask(尽管可能存在边缘情况):

public class UploadFileCommandHandler(IFileUploadingService fileUploadingService) 
    : IRequestHandler<UploadFileCommand>
{
    private readonly IFileUploadingService _fileUploadingService = fileUploadingService;

    public Task Handle(UploadFileCommand request, CancellationToken cancellationToken)
    {
        _fileUploadingService.UploadFile(request.File); // <- this method returns VOID, not a task, see it below (the interface IFileUploadingService)
        return Task.CompletedTask;
    }
}

Csharp相关问答推荐

ASP.NET Core 8 Cors标题未显示

发布.NET框架项目将.NET核心元素注入到web. connect中

SignalR客户端不会打印队列位置'

可为空的泛型属性

Thad.Sept()vs Task.Delay().Wait()

如何将MongoDB序列化程序设置为内部对象属性

如何允许数组接受多个类型?

.Net MAUI,在将FlyoutPage添加到容器之前,必须设置添加构造函数导致Flyout和Detail"

Content WithTargetPath实际上是有效的MSBuild项吗?

为什么我的用户界面对象移动到略低于实际目标?

从Base64转换为不同的字符串返回相同的结果

如何在特定环境中运行dotnet测试?

在.NET Maui中,Flyoutindow/Hamburger菜单可以在shell 之外实现吗?

映射器-如何映射到多个实体

SqlException:无法打开数据库.升级到Dotnet 8后-数据库兼容性版本-非EFCore兼容性级别

如何更改Datagridview行标题

如何对列表<;列表>;使用集合表达式?

为什么INTEGER在通过反射调用时对空对象返回TRUE,而在INTEGER上调用时返回FALSE?

同时通过多个IEumable<;T&>枚举

ASP.NET核心中的验证错误-该字段为必填字段