如何在Hangfire中调用异步方法? [英] How to invoke async methods in Hangfire?

查看:857
本文介绍了如何在Hangfire中调用异步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have asp.net core API application and this is the first time i will be using HangFire.

在.Net Core应用程序中,我所有的方法都是异步的。根据 SO Post ,它不是在hangfire中调用异步方法时使用 wait()的好主意。

另外,根据 hangfire支持问题,添加了异步支持。我正在使用1.6.12版,但仍然看不到异步支持。

In .Net Core application all my methods are async. Based on SO Post it's not good idea to use wait() while calling async method in hangfire.
Also as per the hangfire support issue in v1.6.0, async support was added. I am using version 1.6.12 but still i dont see async support.

如何从入队。目前我正在使用 wait()

How do i call async method from Enqueue. Currently i am using 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());
    }
}


推荐答案

基于在github上的存储库

Based on one of the examples on the repository on github

只需删除等待阻止呼叫

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

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

The method knows now how to handle Func that returns Task

Hangfire 1.6.0-博客


同步和异步方法的入队逻辑相同。在早期的
beta中,有一个警告CS4014,但是现在您可以删除所有的
#pragma 警告禁用语句。通过使用 Expression< Func< Task>> 参数重载来实现。

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));


注意:


这不是真正的异步



请将此功能视为语法糖。后台
处理尚未变为异步。在内部使用Task.Wait方法实现
,因此工作人员在等待任务完成时不会执行任何处理,
。真正的异步可能仅在
Hangfire 2.0中出现,并且需要对
现有类型进行大量重大更改。

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.

这篇关于如何在Hangfire中调用异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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