在没有内置调度程序的平台(Unity)中切换UIThreadDispatcher

时间:2014-03-26 03:19:53

标签: unity3d mvvmcross

我在Unity中使用mvvmcross,但它没有内置的UIThreadDispatcher,有很多人写过它拥有的调度程序并没有一个通用接口。以下是我自己的实现。而不是创建不同的MvxXXXUIThreadDispatcher,还有其他方法吗?

public abstract class MvxUnityUIThreadDispatcher
: MvxMainThreadDispatcher
{
    protected MvxUnityUIThreadDispatcher()
    {
    }

    public bool RequestMainThreadAction(Action action)
    {
        UIThreadDispatcher.Instance.InvokeOrEnqueueOnMainThread(() => ExceptionMaskedAction(action));

        return true;
    }
}

1 个答案:

答案 0 :(得分:0)

Mvx使用线程调度程序来确保不在非UI线程上调用UI控件。

如果Unity不需要此功能,那么您只需在实施中调用action()即可。

https://github.com/et-nowis/mvx-unity-ngui MvvmCross实现中,看起来他们使用了SynchronizationContext

public abstract class MvxUnityUIThreadDispatcher
    : MvxMainThreadDispatcher
{
    private readonly SynchronizationContext _uiSynchronizationContext;

    protected MvxUnityUIThreadDispatcher()
    {
        if (SynchronizationContext.Current == null)
            SynchronizationContext.SetSynchronizationContext(new UnitySynchronizationContext());
        _uiSynchronizationContext = SynchronizationContext.Current;
    }

    public bool RequestMainThreadAction(Action action)
    {
        if (_uiSynchronizationContext == SynchronizationContext.Current)
            action();
        else
            _uiSynchronizationContext.Post(state => ExceptionMaskedAction(action), null);
        return true;
    }
}

来自https://github.com/et-nowis/mvx-unity-ngui/blob/master/Assets/External/MvvmCross/Cirrious/Cirrious.MvvmCross.Unity/Views/MvxUnityUIThreadDispatcher.cs - 请参阅此处的源文件,了解有关此代码的许可条款