简体   繁体   中英

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.

The method calls the asyncCallback correctly, but it steps over that step before all the await from the asynCallback have been executed.

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.

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

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

Another thing you should check is if an exception is thrown from inside the Func

An async method returns when after encounters an await statement and sets up the asynchronous operation being awaited. The rest of the method then continues after the await is finished.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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