Unity3dAsyncAwaitUtil icon indicating copy to clipboard operation
Unity3dAsyncAwaitUtil copied to clipboard

Make some of the async operations cancellable by passing a CancellationToken

Open svermeulen opened this issue 6 years ago • 4 comments

svermeulen avatar Sep 23 '17 07:09 svermeulen

Hi, I was trying to figure out how to do this myself, but if I stop the player before an async method has completed, it will continue to run in editor mode, causing issues. I haven't managed to come up with a working way of cancelling. Here's what I have currently, any suggestions would be greatly appreciated!

private CancellationTokenSource cancelToken;

private void Start()
{
    cancelToken = new CancellationTokenSource();
    Task.Run(() => SetBomb(), cancelToken.Token);
}

private void OnDestroy()
{
    cancelToken.Cancel(false);
}

The problem with that is that unity then complains that I'm performing Unity API calls in SetBomb that aren't in the main thread.

Full script: https://pastebin.com/5DHfNJX0

markffrench avatar Nov 12 '17 12:11 markffrench

Any news on this?

bdominguez avatar Feb 02 '18 09:02 bdominguez

Task.Run creates a thread for you. Should be okay to just run SetBomb directly.

private void Start()
{
    cancelToken = new CancellationTokenSource();
    SetBomb();
}

async Task SetBomb()
{
    // your logic...
    if (cancelToken.IsCancellationRequested)
        return;
    // your logic...
}

favoyang avatar Jun 24 '19 12:06 favoyang

I run an async func in Unity and it will last an long time if user click button I will cancel the async func how can I got this?

ivanleo avatar Nov 20 '19 07:11 ivanleo