无法等待方法组功能委托

时间:2019-05-31 00:09:24

标签: c# async-await

我有一个func委托,其定义如下,

   public enum RunEndStatus
    {
        Success
    }
    public class classA
    {
        Func<object, RunEndStatus> ProcessCalibrationRun { get; set; }
    }

现在在另一个类中,可以说classB我正在做类似的事情,

public class ClassB
{
    public void DoSomething()
    {
        ClassA a = new ClassA();
        a.ProcessCalibrationRun = ProcessCalibrationRun;//This is just fine. It won't complain here.
    }
    public RunEndStatus ProcessCalibrationRun(object obj)
    {
        //Here I have some piece of code takes so much time. To replicate it,
        Thread.Sleep(10000);
    }
}

从某处调用DoSomething方法时,应用程序阻塞了10分钟。因此,我尝试按照以下方式解决问题,

 public async Task<RunEndStatus> ProcessCalibrationRun(object obj)
    {
        await Task.Run(() => { Thread.Sleep(10000)});
        return RunEndStatus.Success;
    }

我正在如下修改通话。但是它说不能等待方法组。请帮助我如何等待该方法。

 public async void DoSomething()
    {
        ClassA a = new ClassA();
        a.ProcessCalibrationRun = await ProcessCalibrationRun; //Here it complains saying cannot await method group.
    }

1 个答案:

答案 0 :(得分:0)

async签名返回一个Task,因此您的Func也需要

public Func<object, Task<RunEndStatus>> ProcessCalibrationRun { get; set; }

这意味着您将不需要async中的DoSomething签名,无论如何都不应该是async void

public void DoSomething()
{
   vara = new ClassA();
   a.ProcessCalibrationRun = ProcessCalibrationRun;
}

然后在其他地方(也许在ClassA中)可以调用它

public async Task DoSomethingElse()
{
   await ProcessCalibrationRun(somethignObject);
}