取消异步操作

Its definitely frustrating theres no StopCoroutine that takes a Coroutine. I rarely ever start them with a string to begin with.

So one way you could accomplish this is by using something like this:

Code:  
  1. class CancellingCoroutine : IEnumerator
  2. {
  3.     public bool stop;
  4.  
  5.     IEnumerator enumerator;
  6.     MonoBehaviour behaviour;
  7.  
  8.     public readonly Coroutine coroutine;
  9.  
  10.     public CoroutineStopable(MonoBehaviour behaviour, IEnumerator enumerator)
  11.     {
  12.         this.behaviour = behaviour;
  13.         this.enumerator = enumerator;
  14.         this.coroutine = behaviour.StartCoroutine(this);
  15.     }
  16.  
  17.     public object Current { get { return enumerator.Current; } }
  18.     public bool MoveNext { return !stop && enumerator.MoveNext(); }
  19.     public void Reset() { enumerator.Reset(); }
  20.     public void Dispose() { enumerator.Dispose(); }
  21.     public implicit operator YieldStatement ( CancellingCoroutine self ) { return self == null ? null : self.coroutine; }
  22. }


Then to start it you would do:

Code:  
  1. CancellingCoroutine ccoroutine = new CancellingCoroutine(this, CoFunctionEnumerator() );

To wait for it

Code:  
  1. yield return ccoroutine.coroutine;

Then to stop it

Code:  
  1. ccoroutine.stop = true;


Its a hacky work around and it would be alot better if YieldStatement wasnt functionally sealed.


If you change your IEnumerator functions to use IEnumerator<YieldStatement> instead it'd be best. But i don't know how that would fair for builtin stuff like Start...

You could also set a done variable in the class when MoveNext returns false, thus allowing you to wait multiple times.

转载unity3d论坛:http://forum.unity3d.com/threads/102817-Coroutine-Control-and-StartCoroutine()-Coroutine

原文地址:https://www.cnblogs.com/newyue/p/3485644.html