landelare / ue5coro

A C++20 coroutine plugin offering seamless integration with Unreal Engine 5.
BSD 3-Clause Clear License
617 stars 57 forks source link

[Question] About TCoroutine lifetime #11

Closed ameaninglessname closed 1 year ago

ameaninglessname commented 1 year ago

I want to start introducing coroutine to my project by using it to solve one replication race condition:


void CallBack()
{
    // normal function part

    auto Coro = [Pawn]() -> UE5Coro::TCoroutine<>
    {
        ON_SCOPE_EXIT
        {
            UE_LOG(LogTemp, Log, TEXT("I am dead")); // (1
        };

        // wait until Pawn has a valid PlayerState
        const auto* PlayerState = co_await Coro_GetPlayerStateFromPawn(Pawn); // (2

        // do stuff with PlayerState

        co_return;
    };
    Coro(); // (3
}

Q1: Why the (1 part not executed after Coro();

the object that Coro() created should get out of scope and destructed, so the related coroutine frame also get destroyed? ("out of scope but can still run" is what a want though, I noticed it was turning into a latent action in FLatentAwaiter::Suspend)

Q2 How to not executing (2 when PIE exit?

I found that if I can't get the PlayerState until PIE exit, the coroutine is resumed to (2, so I need to check PlayerState to prevent crash, but I hope it do not run in this situation.

Tried to cancel, but: image

landelare commented 1 year ago

Not a bug. TCoroutines don't own the coroutine and your lambda is not latent, therefore it cannot use Latent::Cancel.