Unity C# 子线程Action发送到主线程执行

今天去面试..面试官竟然说子线程的Action不能发送到主线程执行... ...废话不说上干货

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Threading;

public class ActionDemo : MonoBehaviour {
	
	public static List<Action<string>> actionlist = new List<Action<string>>();

	void Start()
	{
		actionlist.Add( curname => {
			Debug.Log ("action1 :" + curname);

		});
		actionlist.Add( curname => {
			Debug.Log ("action2 :" + curname);

		});
		//开启子线程
		Thread th = new Thread(ThreadChild);
		th.Start();
	}
	static void ThreadChild()
	{
		//循环三次 关闭线程,养成良好习惯
		for (int i = 0; i < 3; i++) {
			//锁住保证线程安全
			lock(actionlist){
				actionlist.Add( curname => {
					//这里填子线程中 想去主线程调用的代码 ,例如改变UI
					Debug.Log ("ThreadChild :" + curname);

				});
				Thread.Sleep(1000);
			}
		}
	}
	void Update(){
		//遍历action 在Update中调用action自然是主线程调用
		for (int i = 0; i < actionlist.Count; i++) {
			ActionDemo.actionlist [i] (Time.time+"");
		}
		actionlist.Clear();
	}
}


猜你喜欢

转载自blog.csdn.net/u010294054/article/details/80261275