本文介绍了异步/等待Lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题,结合异步/的await,使其工作:
我创建了一个小程序,它应该基本上处理每一个动作的try / catch语句:

I have a strange problem combining the async/await to make it work:I created a small procedure, which should handle basically the try/catch of every action:

    internal static void HandledAction(Action action, Info infoBar)
    {
        try
        {
            action();
        }
        catch (Exception ex)
        {
            infoBar.SetError("An Exception occured: " + ex.Message);
            WriteLog(ex.StackTrace);
        }

Nohing看中,但它是因为改变错误处理是很容易做的价值。
但会发生什么,如果我想获得的数据异步的拉姆达?让我们这个简单的例子:

Nohing to fancy, but it's worth since changing error-handling is very easy made.But what happens, if I'd like to get Data async in the Lambda? Lets take this simple example:

    private void mnuImportData_Click(object sender, RoutedEventArgs e)
    {
        ActionHelper.HandledAction(async () =>
        {
            throw new NotImplementedException("Ups");
        }, infoMain);
    }

当然,HandledAction被调用,传递,因为它得到的指针返回,异常得到投掷,当然不会处理。

Sure, the HandledAction gets called, passes, since it gets the pointer back, and the exception gets thrown, of course not handled.

我想我必须创建一个AsyncHandledAction,并设置异步行动,但有解决这个问题的一个更简单的方法?

I imagine I have to create a AsyncHandledAction, and set the action async, but is there a easier way to solve this problem?

我想很多人都使用中央异常处理,并有更好的方案来解决这个?

I guess many people use a central exception-handling, and there are far better solutions for this?

在此先感谢

马蒂亚斯

编辑:我创建了一个例子,它应该内特shpw我需要:我基本上不想整个动作我正在传递awaitable,但在LAMBDA一个电话是:

I created an example, which should shpw netter I need: I basically dont want the whole Action I pass being awaitable, but one call in the Lambda is:

ActionHelper.HandledActionAsync(() =>
        {
            //elided
            CheckFileResult rslt = await excelImport.CheckFilesAsync(tmpPath);
            //elided
        }, infoMain);

当然,这样做,我得到的错误:

Of course, by doing so, I get the error:

错误3'等待'操作符只能一个异步拉姆达前pression内使用。考虑标志着这个拉姆达前pression与异步修改

Error 3 The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.

推荐答案

您需要HandleAction的异步版本

You need an async version of HandleAction

internal static async Task HandledAction(Func<Task> action, Info infoBar)
{
    try
    {
        await action();
    }
    catch (Exception ex)
    {
        infoBar.SetError("An Exception occured: " + ex.Message);
        WriteLog(ex.StackTrace);
    }
}

当然,你应该调用与等待方法

of course you should call the method with await

private async void mnuImportData_Click(object sender, RoutedEventArgs e)
{
    await ActionHelper.HandledAction(async () =>
    {
        throw new NotImplementedException("Ups");
    }, infoMain);
}

这篇关于异步/等待Lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 08:34