gpt4 book ai didi

c# - 如何在 Hangfire 中调用异步方法?

转载 作者:可可西里 更新时间:2023-11-01 03:13:03 26 4
gpt4 key购买 nike

我有 asp.net 核心 API 应用程序,这是我第一次使用 HangFire。

在 .Net Core 应用程序中,我的所有方法都是异步的。基于SO Post在 hangfire 中调用异步方法时使用 wait() 不是个好主意。
同样根据 hangfire support issue在 v1.6.0 中,添加了异步支持。我使用的是 1.6.12 版,但仍然看不到异步支持。

如何从 Enqueue 调用异步方法。目前我正在使用 wait()

public class MyController : Controller
{
private readonly Downloader _downlaoder;
private readonly IBackgroundJobClient _backgroungJobClient;
public MyController(Downloader downloader, IBackgroundJobClient backgroungJobClient)
{
_downlaoder = downloader;
_backgroungJobClient = backgroungJobClient;
}

[HttpPost]
public void Post([FromBody]IEnumerable<string> files)
{
_backgroungJobClient.Enqueue(() => _downloader.DownloadAsync(files).Wait());
}
}

最佳答案

基于 repository on github 上的示例之一

只需删除 Wait阻塞调用

_backgroungJobClient.Enqueue(() => _downloader.DownloadAsync(files));

该方法现在知道如何处理返回 Task 的 Func

Hangfire 1.6.0 - Blog

The enqueueing logic is the same for sync and async methods. In early betas there was a warning CS4014, but now you can remove all the #pragma warning disable statements. It was implemented by using Expression<Func<Task>> parameter overloads.

BackgroundJob.Enqueue(() => HighlightAsync(snippet.Id));

注意:

That’s not a real asynchrony

Please consider this feature as a syntactic sugar. Background processing hasn’t became asynchronous. Internally it was implemented using the Task.Wait method, so workers don’t perform any processing, while waiting for a task completion. Real asynchrony may come in Hangfire 2.0 only, and it requires a lot of breaking changes to the existing types.

关于c# - 如何在 Hangfire 中调用异步方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43103092/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com