赞
踩
简单写了一份代码,大家可以在Unity中尝试运行一下,希望能够帮助大家理解UniTask的取消方法。
using System; using System.Collections; using System.Collections.Generic; using System.Threading; using Cysharp.Threading.Tasks; using UnityEngine; using UnityEngine.UI; public class LearnTaskFour : MonoBehaviour { public Button btnS; public Button btnE; private CancellationTokenSource _one; private CancellationToken _token; private void Start() { _one = new CancellationTokenSource(); _token = _one.Token; //第一种 使用try Catch得方式 // btnS.onClick.AddListener(async () => // { // try // { // await Run(_token); // } // catch (OperationCanceledException e) // { // Debug.Log(e); // } // }); //第二种 btnS.onClick.AddListener(async () => { bool cancel = await Run(_token).SuppressCancellationThrow(); if (cancel) { Debug.Log("取消"); } }); btnE.onClick.AddListener(async () => { _one.Cancel();//取消 _one.Dispose(); _one = new CancellationTokenSource(); _token = _one.Token; }); } private async UniTask Run(CancellationToken token) { while (true) { await UniTask.NextFrame(token); Debug.Log("执行"); } } }
点击btns时,开始执行
点击btne,取消
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。