Created
May 1, 2018 05:07
-
-
Save tsubaki/d5c293fb23e600c805807e07a208b93c to your computer and use it in GitHub Desktop.
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 System.Collections; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using UnityEngine; | |
using UnityEngine.Profiling; | |
public class NewBehaviourScript : MonoBehaviour | |
{ | |
private const int loopCount = 10000; | |
void Start() | |
{ | |
Debug.Log("start"); | |
DoSomethingAsync(); // 即完了 | |
Debug.Log("end"); | |
} | |
private async void DoSomethingAsync() | |
{ | |
// ---------------------- メインスレッド ---------------------- | |
var context = SynchronizationContext.Current; // 途中経過の取得用にコンテキストを取得しておく | |
var samplerThread = CustomSampler.Create("thread"); // samplerの生成はメインスレッドでのみ可能 | |
var samplerMain = CustomSampler.Create("main"); | |
var pos = transform.position; | |
await Task.Run(() => // ---------------------- ここから別スレッド ---------------------- | |
{ | |
Profiler.BeginThreadProfiling("group", "name"); //BeginThreadProfilingは別スレッドでのみ呼び出せる | |
for (var i = 0; i < loopCount; i++) | |
{ | |
samplerThread.Begin(); // <- プロファイル開始 | |
Debug.Log("重い処理"); // 何か重い処理(I/Oとか) | |
pos += Vector3.up; | |
context.Post((state) => // 途中経過をメインスレッドに反映 | |
{ | |
samplerMain.Begin(); // メインスレッドに戻した先でもプロファイル出来る | |
transform.position = pos; | |
samplerMain.End(); | |
}, null); | |
samplerThread.End();// <- プロファイル終了 | |
} | |
Profiler.EndThreadProfiling(); // ThreadProfilingが使ってたリソースを開放 | |
}); | |
// ---------------------- メインスレッド ---------------------- | |
transform.position = pos; // 処理が終わったので反映 | |
Debug.Log("done"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment