Unity中Task的实现(主线程中的任务式编程)
发表于2017-06-26
以前介绍了如何把Task移植到Unity中使用,毕竟Unity不支持4.x,貌似也没打算支持。但那个Task里面的东西全是在后台线程执行的。虽然可以用类似invoke的方式(这个我有单独的封装,曾经在官网介绍过),切入到主线程进行操作,但是如果遇到我的任务就是个协程,就歇菜了。因为他可不没办法支持协程当任务。于是我就又花了两天时间捣鼓,写了个UTask的模型。这种模型,有好多人已经封装过,但大家出发点各不相同,我是纯粹的希望任务式编程。
先来看结果吧:

顺着之前的那两篇文章,一篇是Task,一篇是协程。这里的思路和之前的Task模式是一致的,唯一的区别就是毕竟这里是unity的主线程,不能直接一个action作为任务,那样会卡死主线程的,所以用了协程来作为任务的单位。顺其自然,任务执行中无选择余地的用了MonoBehaviour中的StartCoroutine和StopCoroutine来启动与取消任务。
但这里有所不同的是我做了一层封装,也就是你看到的Excute这个方法
这么写看起来很诡异吧,因为这样写我可以拿到最后一个yield return的值作为一个协程的返回值。(记住协程本身是没有返回值的,他实际上是个类,他的主体就是movenext,这个在前一篇有过讲解,当然也就不可以使用ref,out来输出了。我也是想了各种办法,最后测试,发现可以用yield return来实现的。)
其实只要你熟悉了之前的Task的机制,再熟悉了这里对任务原型的选择以及任务的启动结束的使用,你也就可以实现了。因为是链式编程,所以有两行代码对你比较有价值,如果你想实现一个和我一样的东西的话。
m_continuationActions存的是任务结束后的action,这个action就是彻底结束了,不会再返回个任务让你继续链路下去。
下一个存在的就是后续的任务,一个任务可以有多个后续任务,虽然一般情形我们是A->b->c->d。但也有很多A结束后同时运行b和c两个或若干个任务。
当然有扇出,肯定有扇入。所以有WhenAll和WhenAny
另外可能需要补充下的就是,启动任务的方法原型为
至此,如果你愿意,花费一两天时间,你也能实现你的版本。欢迎交流。
上面的是MainThread的Task,前面的那篇是Backgroud的Task。但是我们正常使用中很多场景是需要前台切后台,后台处理完了切入前台。以前我们都是通过各种锁信号来实现异步与同步的概念。如果使用Task的概念,则只要针对foregroud的task提供切入后台task的方法,backgroud的task提供切入前台的方法即可。
然后就可以方便的前台后台切换
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public class Test : MonoBehaviour { // Use this for initialization void Start() { var task1 = Dpjia.UnityTask.UTask.Run< int >(() => AA()).ContinueWith< int >(t => BB(t)); } IEnumerator AA() { int res = 100; Debug.Log( "AA: " + res + " " + Time.time); yield return new WaitForSeconds(2); res += 50; Debug.Log( "AA: " + res + " " + Time.time); yield return res; } IEnumerator BB(UTask< int > p_task) { int res = p_task.Result; yield return new WaitForSeconds(1); Debug.Log( "BB: " + res + " " + Time.time); yield return new WaitForSeconds(1); res *= 2; Debug.Log( "BB: " + res + " " + Time.time); yield return null ; } } |

使用这种方案,我们可以拆分我们的业务为一个个独立的任务,然后顺序去执行就行了。
顺着之前的那两篇文章,一篇是Task,一篇是协程。这里的思路和之前的Task模式是一致的,唯一的区别就是毕竟这里是unity的主线程,不能直接一个action作为任务,那样会卡死主线程的,所以用了协程来作为任务的单位。顺其自然,任务执行中无选择余地的用了MonoBehaviour中的StartCoroutine和StopCoroutine来启动与取消任务。
01 02 03 04 05 06 07 08 09 10 11 12 | ///
/// Dispatches an asynchronous message to coroutine. /// /// public Coroutine Post(IEnumerator p_action, Action< object > p_completeCallback) { return g_defaultContext.StartCoroutine(Excute(p_action, p_completeCallback)); } public void Stop(Coroutine p_coroutine) { StopCoroutine(p_coroutine); } |
但这里有所不同的是我做了一层封装,也就是你看到的Excute这个方法
01 02 03 04 05 06 07 08 09 10 | private static IEnumerator Excute(IEnumerator p_coroutine, Action< object > p_completeCallback) { while (p_coroutine.MoveNext()) { yield return p_coroutine.Current; } if (p_completeCallback != null ) { p_completeCallback(p_coroutine.Current); } } |
这么写看起来很诡异吧,因为这样写我可以拿到最后一个yield return的值作为一个协程的返回值。(记住协程本身是没有返回值的,他实际上是个类,他的主体就是movenext,这个在前一篇有过讲解,当然也就不可以使用ref,out来输出了。我也是想了各种办法,最后测试,发现可以用yield return来实现的。)
其实只要你熟悉了之前的Task的机制,再熟悉了这里对任务原型的选择以及任务的启动结束的使用,你也就可以实现了。因为是链式编程,所以有两行代码对你比较有价值,如果你想实现一个和我一样的东西的话。
1 | protected List m_continuationActions = new List(); protected List m_continuationTasks = new List(); |
m_continuationActions存的是任务结束后的action,这个action就是彻底结束了,不会再返回个任务让你继续链路下去。
下一个存在的就是后续的任务,一个任务可以有多个后续任务,虽然一般情形我们是A->b->c->d。但也有很多A结束后同时运行b和c两个或若干个任务。
当然有扇出,肯定有扇入。所以有WhenAll和WhenAny
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | ///
/// Creates a task that is complete when all of the provided tasks are complete. /// If any of the tasks has an exception, all exceptions raised in the tasks will /// be aggregated into the returned task. Otherwise, if any of the tasks is cancelled, /// the returned task will be cancelled. /// /// The tasks to aggregate. /// A task that is complete when all of the provided tasks are complete. public static UTask WhenAll(IEnumerable p_tasks) { var taskArr = p_tasks.ToArray(); if (taskArr.Length == 0) { return UTask.FromResult(0); } var tcs = new UTaskCompletionSource< object >(); UTask.Factory.ContinueWhenAll(taskArr, _ => { var exceptions = taskArr.Where(p => p.IsFaulted).Select(p => p.Exception).ToArray(); if (exceptions.Length > 0) { tcs.SetException( new System.Threading.Tasks.AggregateException(exceptions)); } else if (taskArr.Any(t => t.IsCanceled)) { tcs.SetCanceled(); } else { tcs.SetResult(0); } }); return tcs.Task; } |
01 02 03 04 05 06 07 08 09 10 11 12 13 | ///
/// Waits for any of the provided Task objects to complete execution. /// /// /// internal static UTask WhenAny(IEnumerable p_tasks) { var tcs = new UTaskCompletionSource(); foreach (var task in p_tasks) { task.ContinueWith(t => tcs.TrySetResult(t)); } return tcs.Task; } |
另外可能需要补充下的就是,启动任务的方法原型为
[C#] 纯文本查看 复制代码
1 2 3 4 5 6 | ///
/// Creates and starts a Task /// /// /// /// public UTask StartNew(Func p_func) |
至此,如果你愿意,花费一两天时间,你也能实现你的版本。欢迎交流。
上面的是MainThread的Task,前面的那篇是Backgroud的Task。但是我们正常使用中很多场景是需要前台切后台,后台处理完了切入前台。以前我们都是通过各种锁信号来实现异步与同步的概念。如果使用Task的概念,则只要针对foregroud的task提供切入后台task的方法,backgroud的task提供切入前台的方法即可。
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095 096 097 098 099 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | ///
/// switch to backgroud processor, thread pool /// /// /// /// /// public static Task ContinueToBackground( this UTask p_task, Func p_continuation) { return p_task.ContinueToBackground(p_continuation, CancellationToken.None); } ///
/// switch to backgroud processor, thread pool /// /// /// /// /// public static Task ContinueToBackground( this UTask p_task, Func p_continuation, CancellationToken p_cancellationToken) { TaskCompletionSource tcs = new TaskCompletionSource(); var cancellation = p_cancellationToken.Register(() => tcs.TrySetCanceled()); p_task.ContinueWith(t => { TaskScheduler.FromCurrentSynchronizationContext().Post(() => { try { tcs.SetResult(p_continuation()); cancellation.Dispose(); } catch (Exception e) { tcs.SetException(e); cancellation.Dispose(); } }); }); return tcs.Task; } ///
/// switch to backgroud processor, thread pool /// /// /// /// /// public static Task ContinueToBackground( this UTask p_task, Func p_continuation) { return p_task.ContinueToBackground(p_continuation, CancellationToken.None); } ///
/// switch to backgroud processor, thread pool /// /// /// /// /// public static Task ContinueToBackground( this UTask p_task, Func p_continuation, CancellationToken p_cancellationToken) { TaskCompletionSource tcs = new TaskCompletionSource(); var cancellation = p_cancellationToken.Register(() => tcs.TrySetCanceled()); p_task.ContinueWith(t => { TaskScheduler.FromCurrentSynchronizationContext().Post(() => { try { tcs.SetResult(p_continuation(t)); cancellation.Dispose(); } catch (Exception e) { tcs.SetException(e); cancellation.Dispose(); } }); }); return tcs.Task; } ///
/// switch to backgroud processor, thread pool /// /// /// /// /// public static Task ContinueToBackground( this UTask p_task, Action p_continuation, CancellationToken p_cancellationToken) { TaskCompletionSource< object > tcs = new TaskCompletionSource< object >(); var cancellation = p_cancellationToken.Register(() => tcs.TrySetCanceled()); p_task.ContinueWith(t => { TaskScheduler.FromCurrentSynchronizationContext().Post(() => { try { p_continuation(); tcs.SetResult( null ); cancellation.Dispose(); } catch (Exception e) { tcs.SetException(e); cancellation.Dispose(); } }); }); return tcs.Task; } ///
/// switch to backgroud processor, thread pool /// /// /// /// /// public static Task ContinueToBackground( this UTask p_task, Action p_continuation) { return p_task.ContinueToBackground(p_continuation, CancellationToken.None); } ///
/// switch to backgroud processor, thread pool /// /// /// /// /// public static Task ContinueToBackground( this UTask p_task, Action p_continuation, CancellationToken p_cancellationToken) { TaskCompletionSource< object > tcs = new TaskCompletionSource< object >(); var cancellation = p_cancellationToken.Register(() => tcs.TrySetCanceled()); p_task.ContinueWith(t => { TaskScheduler.FromCurrentSynchronizationContext().Post(() => { try { p_continuation(t); tcs.SetResult( null ); cancellation.Dispose(); } catch (Exception e) { tcs.SetException(e); cancellation.Dispose(); } }); }); return tcs.Task; } ///
/// switch to backgroud processor, thread pool /// /// /// /// /// public static Task ContinueToBackground( this UTask p_task, Action p_continuation) { return p_task.ContinueToBackground(p_continuation, CancellationToken.None); } ///
/// switch to backgroud processor, ForegroundInvoker /// /// /// /// /// public static void ContinueToForeground( this Task p_task, Action p_continuation) { p_task.ContinueWith(t => { Dpjia.Processor.ForegroundInvoker.Invoke(() => { p_continuation(); }); }); } ///
/// switch to backgroud processor, ForegroundInvoker /// /// /// /// /// public static void ContinueToForeground( this Task p_task, Action p_continuation) { p_task.ContinueWith(t => { Dpjia.Processor.ForegroundInvoker.Invoke(() => { p_continuation(t); }); }); } ///
/// switch to backgroud processor, ForegroundInvoker /// /// /// /// /// public static UTask ContinueToForeground( this Task p_task, Func p_continuation, CancellationToken p_cancellationToken) { UTaskCompletionSource tcs = new UTaskCompletionSource(); var cancellation = p_cancellationToken.Register(() => tcs.TrySetCanceled()); tcs.Task.TaskGenerator = p_continuation; tcs.Task.ReturnResult = p => { try { tcs.SetResult((TResult)p); cancellation.Dispose(); } catch (Exception e) { tcs.SetException(e); cancellation.Dispose(); } }; p_task.ContinueWith(t => { Dpjia.Processor.ForegroundInvoker.Invoke(() => { UTaskScheduler.FromCurrentSynchronizationContext().Post(tcs.Task.TaskGenerator(), tcs.Task.ReturnResult); }); }); return tcs.Task; } ///
/// switch to backgroud processor, thread pool /// /// /// /// /// public static UTask ContinueToForeground( this Task p_task, Func p_continuation) { return p_task.ContinueToForeground(p_continuation, CancellationToken.None); } ///
/// switch to backgroud processor, ForegroundInvoker /// /// /// /// /// public static UTask ContinueToForeground( this Task p_task, Func p_continuation, CancellationToken p_cancellationToken) { UTaskCompletionSource tcs = new UTaskCompletionSource(); var cancellation = p_cancellationToken.Register(() => tcs.TrySetCanceled()); tcs.Task.TaskGenerator = () => p_continuation(p_task); tcs.Task.ReturnResult = p => { try { tcs.SetResult((TResult)p); cancellation.Dispose(); } catch (Exception e) { tcs.SetException(e); cancellation.Dispose(); } }; p_task.ContinueWith(t => { Dpjia.Processor.ForegroundInvoker.Invoke(() => { UTaskScheduler.FromCurrentSynchronizationContext().Post(tcs.Task.TaskGenerator(), tcs.Task.ReturnResult); }); }); return tcs.Task; } ///
/// switch to backgroud processor, ForegroundInvoker /// /// /// /// /// public static UTask ContinueToForeground( this Task p_task, Func p_continuation) { return p_task.ContinueToForeground(p_continuation, CancellationToken.None); } |
然后就可以方便的前台后台切换
[AppleScript] 纯文本查看 复制代码
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | / / Use this for initialization void Start ( ) { Dpjia.Processor.ForegroundInvoker.Initialize ( ) ; Debug.Log ( Thread.CurrentThread.ManagedThreadId ) ; UTask.Run < int > ( ( ) = > AA ( ) ) .ContinueWith < int > ( t = > BB ( t ) ) .ContinueToBackground ( ( ) = > { Debug.Log ( Thread.CurrentThread.ManagedThreadId ) ; } ) .ContinueToForeground ( ( ) = > { Debug.Log ( Thread.CurrentThread.ManagedThreadId ) ; } ) ; } IEnumerator AA ( ) { int res = 100 ; Debug.Log ( "AA: " + res + " " + Time.time ) ; yield return new WaitForSeconds ( 2 ) ; res + = 50 ; Debug.Log ( "AA: " + res + " " + Time.time ) ; yield return res; } IEnumerator BB ( UTask < int > p_task ) { int res = p_task.Result; yield return new WaitForSeconds ( 1 ) ; Debug.Log ( "BB: " + res + " " + Time.time ) ; yield return new WaitForSeconds ( 1 ) ; res * = 2 ; Debug.Log ( "BB: " + res + " " + Time.time ) ; yield return null; } |
