modesttree / Unity3dAsyncAwaitUtil

A bunch of code to make using async-await easier in Unity3D
MIT License
454 stars 120 forks source link

Make some of the async operations cancellable by passing a CancellationToken #1

Open svermeulen opened 6 years ago

markffrench commented 6 years ago

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

bdominguez commented 6 years ago

Any news on this?

favoyang commented 5 years ago

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...
}
ivanleo commented 4 years ago

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?