简体   繁体   English

异步委托回调未完全执行

[英]Async delegate callbacks not fully executing

I have an async method MyActionAsync , which receives as a parameter an async Func<int, Task> as a callback. 我有一个异步方法MyActionAsync ,该方法接收异步Func<int, Task>作为回调作为参数。

The method calls the asyncCallback correctly, but it steps over that step before all the await from the asynCallback have been executed. 该方法正确地调用了asyncCallback,但是在执行了来自aynCallback的所有await之前,它会逐步执行该步骤。

This creates some big problems for me. 这给我带来了一些大问题。

How / what can i use to make sure that the like await asyncCallback(id) will step over only when the asyncCallback has completely executed. 我如何/可以用来确保仅在asyncCallback完全执行后才await asyncCallback(id)之类的内容。

public class MyService
{
    public async Task<int> MyActionAsync(int id, Func<int, Task> asyncCallback)
    {
        // 1. do something

        // 2. execute the callback function
        // Steps over this step after the first await is finished, and not when all of them are finished
        await asyncCallback(id);

        // 3. return
        return id;
    }
}

async Task Test()
{
    Func<int, Task> asyncCallback =
        async (id) =>
        {
            var products = await _unitOfWork.Products.Where(p => p.UserId == id).ToListAsync();
            var pictures = await _unitOfWork.Pictures.Where(p => p.UserId == id).ToListAsync();
        };

    MyService service = new MyService();

    await service.MyActionAsync(1, asyncCallback);
}

The code seems ok 该代码似乎还可以

It should wait for the asyncCallback to be finnished 它应该等待asyncCallback完成

How do you know it does not wait for it to be over? 您怎么知道它不等待结束?

Maybe it seems like it's not waiting till it's over because the debugger wont step into the Func when you press F11, it will step into only if you put a breakpoint inside 似乎似乎没有等到结束,因为当您按F11键时调试器不会进入Func,只有在内部插入断点时,调试器才会进入

Another thing you should check is if an exception is thrown from inside the Func 您应该检查的另一件事是,是否从Func内部引发了异常

An async method returns when after encounters an await statement and sets up the asynchronous operation being awaited. 当遇到await语句并设置正在等待的异步操作时, async方法将返回。 The rest of the method then continues after the await is finished. 然后, await完成后,其余方法将继续。

I don't believe you can step through async methods like that, but if you put in some Console.WriteLine statements you should see what you expect. 我不相信您可以逐步执行类似的async方法,但是如果您输入一些Console.WriteLine语句,您应该会看到期望的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM