Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
svermeulen opened this issue Sep 23, 2017 · 4 comments

Comments

@svermeulen
Copy link
Contributor

No description provided.

@markffrench
Copy link

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
Copy link

bdominguez commented Feb 2, 2018

Any news on this?

@favoyang
Copy link

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
Copy link

ivanleo commented Nov 20, 2019

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants