Last active
April 24, 2018 11:01
-
-
Save st0326s/f634826d712ba1605d9e1c8efb2c131b to your computer and use it in GitHub Desktop.
Unity Task実行 Taskキャンセル async await メモ ref: https://qiita.com/satotin/items/4f9fb20cefc057d7641b
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.UI; | |
using System.Threading; | |
using System.Threading.Tasks; | |
public class TaskTest : MonoBehaviour { | |
// MainThreadのコンテキストを取得. | |
SynchronizationContext context = null; | |
CancellationTokenSource tokenSource = new CancellationTokenSource(); | |
[SerializeField] | |
private Text TestLabel; | |
public void OnClickAwaitButton() | |
{ | |
Debug.Log("OnClickAwaitButton() S"); | |
// MainThreadのコンテキストを取得. | |
context = SynchronizationContext.Current; | |
Work(); | |
Debug.Log("OnClickAwaitButton() E"); | |
} | |
/// <summary> | |
/// async・awaitを使ってTaskを処理する | |
/// </summary> | |
/// <returns></returns> | |
async Task Work() | |
{ | |
Debug.Log("実行開始"); | |
await Task.Run(() => | |
{ | |
MethodC(); | |
MethodD(); | |
EndMethod(); | |
}); | |
Debug.Log("実行終了"); | |
} | |
void MethodC() | |
{ | |
for (int i = 0; i < 10000; i++) | |
{ | |
Debug.Log("MethodC=" + i.ToString()); | |
// Taskのキャンセルチェック。 | |
if (tokenSource.Token.IsCancellationRequested) | |
{ | |
Debug.Log("MethodC Cancel"); | |
return; | |
} | |
// メインスレッド側の処理を行う | |
context.Post((state) => | |
{ | |
TestLabel.text = i.ToString(); | |
} | |
, null); | |
} | |
} | |
void MethodD() | |
{ | |
for (int j = 10000; j < 20000; j++) | |
{ | |
Debug.Log("MethodD=" + j.ToString()); | |
// Taskのキャンセルチェック。 | |
if (tokenSource.Token.IsCancellationRequested) | |
{ | |
Debug.Log("MethodD Cancel"); | |
return; | |
} | |
// メインスレッド側の処理を行う | |
context.Post((state) => | |
{ | |
TestLabel.text = j.ToString(); | |
} | |
, null); | |
} | |
} | |
void EndMethod() | |
{ | |
Debug.Log("EndMethod"); | |
// Taskのキャンセルチェック。 | |
if (tokenSource.Token.IsCancellationRequested) | |
{ | |
Debug.Log("EndMethod() Cancel"); | |
return; | |
} | |
// メインスレッド側の処理を行う | |
context.Post((state) => | |
{ | |
TestLabel.text = "終了!"; | |
} | |
, null); | |
} | |
/// <summary> | |
/// キャンセルボタン | |
/// </summary> | |
public void OnClickCancelButton() | |
{ | |
Debug.Log("OnClickCancelButton() S"); | |
// トークンを使って、Taskをキャンセルする。 | |
tokenSource.Cancel(); | |
Debug.Log("OnClickCancelButton() E"); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment