首页 > 编程语言 > 详细

Zenject与UniRx结合实现跨线程通信Signal

时间:2017-09-10 14:05:18      阅读:521      评论:0      收藏:0      [点我收藏+]
  •   修改Zenject下ProfileBlock.cs源码, 取消有关UnityEngine.Profiling.Profiler的代码.
  •   然后使用Zenject的Signal:
技术分享
   // 定义Signal
    public class TestCrossThreadCommEvent : Signal<string, TestCrossThreadCommEvent> { }
View Code
技术分享
1   // Install Signals
2     Container.DeclareSignal<TestCrossThreadCommEvent>();
View Code
技术分享
 1 // 启动线程
 2     tth = new Thread(() =>
 3     {
 4         while (true)
 5         {
 6             Thread.Sleep(1000);
 7             _crossThreadCommEvent.Fire("fire not in main thread");
 8             //_unityEvent.Invoke();
 9         }
10     });
11     tth.Start();
12     // UniRx
13     _crossThreadCommEvent.AsObservable.ObserveOnMainThread(MainThreadDispatchType.Update)
14         // 使用lambda表达式是没有问题的
15         .Subscribe(s => TestCrossThreadComm(s))
16         .AddTo(this);
17     
18     void TestCrossThreadComm(string msg)
19     {
20         Debug.Log(Thread.CurrentThread.ManagedThreadId);
21         Debug.Log(msg);
22         transform.RotateAround(transform.position, Vector3.up, 5f);
23     }
View Code
  •  输出结果:
      1
      UnityEngine.Debug:Log(Object)
      fire not in main thread
      UnityEngine.Debug:Log(Object) 
 
  • 多个参数情况:
技术分享
1 // 定义Signal
2 public class TestCrossThreadCommEvent : Signal<string, string, TestCrossThreadCommEvent> { }
View Code
技术分享
1 // Install Signals
2 Container.DeclareSignal<TestCrossThreadCommEvent>();
View Code
技术分享
 1 // 启动线程
 2 tth = new Thread(() =>
 3 {
 4     while (true)
 5     {
 6         Thread.Sleep(1000);
 7         _crossThreadCommEvent.Fire("fire not in main thread", "\t so happy.");
 8         //_unityEvent.Invoke();
 9     }
10 });
11 tth.Start();
12 // UniRx-Lambda
13 _crossThreadCommEvent.AsObservable.ObserveOnMainThread(MainThreadDispatchType.Update)
14     // 使用lambda表达式是没有问题的
15     .Subscribe(tuple =>
16     {
17         Debug.Log(Thread.CurrentThread.ManagedThreadId);
18         Debug.Log(tuple.Item1 + tuple.Item2);
19         transform.RotateAround(transform.position, Vector3.up, 5f);
20     })
21     .AddTo(this);
View Code
  •  输出结果:
1
UnityEngine.Debug:Log(Object)
fire not in main thread     so happy.
UnityEngine.Debug:Log(Object)

Zenject与UniRx结合实现跨线程通信Signal

原文:http://www.cnblogs.com/linxmouse/p/7500923.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!