- 修改Zenject下ProfileBlock.cs源码, 取消有关UnityEngine.Profiling.Profiler的代码.
- 然后使用Zenject的Signal:
// 定义Signal
public class TestCrossThreadCommEvent : Signal<string, TestCrossThreadCommEvent> { }
// Install Signals
Container.DeclareSignal<TestCrossThreadCommEvent>();
// 启动线程
tth = new Thread(() =>
{
while (true)
{
Thread.Sleep();
_crossThreadCommEvent.Fire("fire not in main thread");
//_unityEvent.Invoke();
}
});
tth.Start();
// UniRx
_crossThreadCommEvent.AsObservable.ObserveOnMainThread(MainThreadDispatchType.Update)
// 使用lambda表达式是没有问题的
.Subscribe(s => TestCrossThreadComm(s))
.AddTo(this); void TestCrossThreadComm(string msg)
{
Debug.Log(Thread.CurrentThread.ManagedThreadId);
Debug.Log(msg);
transform.RotateAround(transform.position, Vector3.up, 5f);
}
- 输出结果:
1
UnityEngine.Debug:Log(Object)
fire not in main thread
UnityEngine.Debug:Log(Object)
- 多个参数情况:
// 定义Signal
public class TestCrossThreadCommEvent : Signal<string, string, TestCrossThreadCommEvent> { }
// Install Signals
Container.DeclareSignal<TestCrossThreadCommEvent>();
// 启动线程
tth = new Thread(() =>
{
while (true)
{
Thread.Sleep();
_crossThreadCommEvent.Fire("fire not in main thread", "\t so happy.");
//_unityEvent.Invoke();
}
});
tth.Start();
// UniRx-Lambda
_crossThreadCommEvent.AsObservable.ObserveOnMainThread(MainThreadDispatchType.Update)
// 使用lambda表达式是没有问题的
.Subscribe(tuple =>
{
Debug.Log(Thread.CurrentThread.ManagedThreadId);
Debug.Log(tuple.Item1 + tuple.Item2);
transform.RotateAround(transform.position, Vector3.up, 5f);
})
.AddTo(this);
- 输出结果:
1
UnityEngine.Debug:Log(Object)
fire not in main thread so happy.
UnityEngine.Debug:Log(Object)
以上为Asset Store中Zenject早期版本.

目前有版本对Signal部分改动如下:
...
#if UNITY_EDITOR && ZEN_PROFILING_ENABLED
using (ProfileBlock.Start("Signal '{0}'", this.GetType().Name))
#endif
{
var wasHandled = Manager.Trigger(SignalId, new object[]); wasHandled |= (_listeners.Count > ); // Iterate over _tempListeners in case the
// listener removes themselves in the callback
// (we use _tempListeners to avoid memory allocs)
_tempListeners.Clear(); for (int i = ; i < _listeners.Count; i++)
{
_tempListeners.Add(_listeners[i]);
} for (int i = ; i < _tempListeners.Count; i++)
{
var listener = _tempListeners[i]; #if UNITY_EDITOR && ZEN_PROFILING_ENABLED
using (ProfileBlock.Start(listener.ToDebugString()))
#endif
{
listener();
}
} #if ZEN_SIGNALS_ADD_UNIRX
wasHandled |= _observable.HasObservers;
#if UNITY_EDITOR && ZEN_PROFILING_ENABLED
using (ProfileBlock.Start("UniRx Stream"))
#endif
{
_observable.OnNext(Unit.Default);
}
#endif
...
涉及到ProfileBlock的使用ZEN_PROFILING_ENABLED来开启, 所以想用Signal跨线程通信,否决掉ZEN_PROFILING_ENABLED就可以了.