Skip to content

Instantly share code, notes, and snippets.

@HarukaKajita
Created April 24, 2021 08:35
Show Gist options
  • Save HarukaKajita/40ced914df07af49dc2197209522681a to your computer and use it in GitHub Desktop.
Save HarukaKajita/40ced914df07af49dc2197209522681a to your computer and use it in GitHub Desktop.
unityで非同期処理のテスト
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Debug = UnityEngine.Debug;
public class AsyncTest : MonoBehaviour {
List<int> results = new List<int>();
void Start() { }
[ContextMenu("Do Sync")]
void InitSync() {
var sw = new Stopwatch();
sw.Start();
var values = new List<int>();
for (int i = 0; i < 10; i++) {
Thread.Sleep(100);
values.Add(i);
}
sw.Stop();
Debug.Log(sw.ElapsedMilliseconds);
var str = "";
foreach (var value in values) {
str += value + ", ";
}
Debug.Log(str);
}
//完了後に結果をリストに詰める(こっちの方が0.数ミリ秒くらい速い)
[ContextMenu("Do Async")]
async Task InitAsync() {
var sw = new Stopwatch();
sw.Start();
var tasks = new List<Task<int>>();
for (int i = 0; i < 10; i++) { tasks.Add(Cal(i)); }
await Task.WhenAll(tasks);
sw.Stop();
Debug.Log(sw.ElapsedMilliseconds);
var str = "";
foreach (var value in tasks.Select(t => t.Result)) {
str += value + ", ";
}
Debug.Log(str);
}
async Task<int> Cal(int x) {
await Task.Delay(100);
return await Task.Run<int>(() => x);
}
//完了後ではなく非同期メソッドから直接リストにアクセスしてみる
[ContextMenu("Do Async Direct Access List")]
async Task InitAsyncDirectAccess() {
results = Enumerable.Repeat(0, 10).ToList();//reset
var sw = new Stopwatch();
sw.Start();
var tasks = new List<Task<int>>();
for (int i = 0; i < 10; i++) { tasks.Add(CalDirectAccess(i)); }
await Task.WhenAll(tasks);
sw.Stop();
Debug.Log(sw.ElapsedMilliseconds);
var str = "";
foreach (var value in results) {
str += value + ", ";
}
Debug.Log(str);
}
async Task<int> CalDirectAccess(int x) {
await Task.Delay(100);
return await Task.Run(() => {
return results[x] = x;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment