如何取消MediatR发送的查询?

How to cancel the query sent by MediatR?

我在 .Net core 3.1 Blazor 应用程序中使用 MediatR。以下是查询及其处理程序。

public class GetSaleQuery : IRequest<SaleVm>
{
    public GetSaleQuery(string id)
    {
        Id = id;
    }

    public string Id { get; }
}

public class GetSaleQueryHandler : IRequestHandler<GetaQuery, SaleVm>
{
    public async Task<SaleVm> Handle(GetSaleQuery request, CancellationToken cancellationToken)
    {
        var q = await _context.Table1
            .ToListAsync(cancellationToken).ConfigureAwait(false);
        return ...;
    }
}

而在UI部分,下面是用来发送查询请求的。

async Task SearchClicked() 
{
    sendResult = await mediator.Send(new GetSaleQuery{ Id = id });
    // page will use sendRest to display the result  .....
}

现在我需要添加一个取消按钮来让用户取消长 运行 查询。如何将取消令牌传递给查询处理程序 GetSaleQueryHandler.Handle()?

async Task CancelButtonClicked() 
{
    // ?????
}

这基本上就是取消令牌的用途,如果您查看 mediatr Send 方法,您会发现它有一个取消令牌作为可选参数:

Task<object> Send(object request, CancellationToken cancellationToken = default (CancellationToken));

您可以在这里阅读更多关于它们的信息:https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken?view=netframework-4.8

A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource.Token property. You then pass the cancellation token to any number of threads, tasks, or operations that should receive notice of cancellation. The token cannot be used to initiate cancellation. When the owning object calls CancellationTokenSource.Cancel, the IsCancellationRequested property on every copy of the cancellation token is set to true. The objects that receive the notification can respond in whatever manner is appropriate.

因此,当您 运行 您想要 return 取消标记的查询时,按照您的要求进行操作:

CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;

var result = await _mediator.Send(new Operation(), token);
return source ;

然后当您取消时,您需要使用该取消令牌来取消操作:

void Cancel(CancellationTokenSource token)
{
  token.Cancel();
}

希望这对您有所帮助。