Unity3dAsyncAwaitUtil
Unity3dAsyncAwaitUtil copied to clipboard
Make some of the async operations cancellable by passing a CancellationToken
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
Any news on this?
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...
}
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?