使用HangFire调用动作委托会产生异常

问题描述 投票:1回答:1

我正在尝试使用HangFire在类上调用操作方法。从下面的代码中,如果在HangFire之外调用action方法,则该方法可以正常工作,但是在使用HangFire时会引发异常。我也尝试使用Invoke(),如其他类似文章所述。

表达主体应为类型'MethodCallExpression'(Parameter'methodCall')'

[我想弄清楚如何让HangFire执行这种方法。

class Program
{
    static void Main(string[] args)
    {
        var a = new ActionTest();

        // Calling this method prints out Hello World correctly
        a.DoAction();

        GlobalConfiguration.Configuration.UseSqlServerStorage(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Test;Integrated Security=True");

        // Call this method from HangFire produces exception: Expression body should be of type 'MethodCallExpression'(Parameter'methodCall')'
        BackgroundJob.Enqueue<ActionTest>(a => a.DoAction());
    }
}


public class ActionTest
{
    public ActionTest()
    {
        DoAction = WriteHello;
    }
    public Action DoAction;

    public void WriteHello()
    {
        Console.WriteLine("Hello World");
    }
}
hangfire
1个回答
0
投票

除了用真正的方法将调用包装到DoAction之外,没有其他方法:

public class ActionTest
{
    public ActionTest()
    {
        DoAction = WriteHello;
    }
    public Action DoAction;

    public void InvokeAction()
    {
        DoAction();
    }

    public void WriteHello()
    {
        Console.WriteLine("Hello World");
    }
}

然后

BackgroundJob.Enqueue<ActionTest>(a => a.InvokeAction());
© www.soinside.com 2019 - 2024. All rights reserved.