首页 > 解决方案 > CS4010 如何将异步 lambda 表达式转换为委托类型“TaskAction”

问题描述

我收到以下错误

错误 CS4010 无法将异步 lambda 表达式转换为委托类型“TaskAction”。异步 lambda 表达式可能返回 void、Task 或 Task,它们都不能转换为“TaskAction”

我的功能如下所示:

public async void GetLastKnownUpdateStatus(string UUIDStr, short ClientId)
{
    UpdateStatusInfo x = new UpdateStatusInfo();
    if (Execution.WaitForTask(async (canceltoken) => { x = await GetLastKnownUpdateStatus(UUIDStr, ClientId); return true; }) > Execution.WAIT_TIMEOUT)
    {
        Output.WriteLine("GetLastKnownUpdateStatus: "+ x.State.ToString());
    }
}

此方法调用以下函数:

public Task<UpdateStatusInfo> GetLastKnownUpdateStatus(string uniqueUpdateID, short clientID)
{
    return GetLastKnownUpdateStatus(uniqueUpdateID, clientID, null);
}

任何帮助表示赞赏

Execution.WaitForTask 来自 Vector.CANoe.Threading 类,由 Vector 定义如下

//
// Summary:
//     Executes a task in a separate thread. During the wait, the measurement and simulation
//     are not blocked. Optionally returns failure after a certain timespan.
//
// Parameters:
//   taskAction:
//     A delegate function to execute in a separate task
//
//   maxTime:
//     Optional: maximum time to wait, in milliseconds.
//
// Returns:
//     WAIT_TIMEOUT: if an maxTime was defined and the task did not return within maxTime
//     milliseconds WAIT_ABORTED: if the measurement was stopped during task execution
//     WAIT_EXCEPTION: if an exception occurred in the taskAction delegate WAIT_ILLEGAL_RESULTVALUE:
//     the result provided by the task is <= 0 > 0 any positive result provided by the
//     taskAction delegate (only use numbers > 0 as return values)
//
// Remarks:
//     Be careful: You may not use most of the CANoe API functions in the taskAction.
//     Allowed is: Modifying SystemVariables Using Output.* functions See documentation
//     for details

标签: c#asynchronouslambdadelegatescanoe

解决方案


TaskAction可能不是异步表达式。它必须是同步的。CANoe 的框架将确保它在后台任务中执行。

最好GetLastKnownUpdateStatus是像这样直接调用最终调用的任何同步方法

public async void GetLastKnownUpdateStatus(string UUIDStr, short ClientId)
{
    UpdateStatusInfo x = new UpdateStatusInfo();
    if (Execution.WaitForTask((canceltoken) => {
          x = GetLastKnownUpdateStatusSync(UUIDStr, ClientId); return true;
        }
    ) > Execution.WAIT_TIMEOUT)
    {
        Output.WriteLine("GetLastKnownUpdateStatus: "+ x.State.ToString());
    }
}

或等待 lambda 中的调用:

public async void GetLastKnownUpdateStatus(string UUIDStr, short ClientId)
{
    UpdateStatusInfo x = new UpdateStatusInfo();
    if (Execution.WaitForTask((canceltoken) => { 
          x = GetLastKnownUpdateStatus(UUIDStr, ClientId).ConfigureAwait(false).GetAwaiter().GetResult(); return true;
        }
    ) > Execution.WAIT_TIMEOUT)
    {
        Output.WriteLine("GetLastKnownUpdateStatus: "+ x.State.ToString());
    }
}

推荐阅读