UI线程问题与MVVMCross中的视图模型

img*_*gen 3 mvvm mvvmcross

我正在使用MVVMCross和我的跨平台Windows Phone和Android应用程序.在核心项目的主视图模型中,我正在使用TPL进行一些后台工作,我想确保在回调中,当我更改视图模型的属性时将触发UI更改,代码运行在UI线程,我该如何实现?

对于代码,这是它喜欢的方式

    private MvxGeoLocation _currentLocation;
    private Task<MvxGeoLocation> GetCurrentLocation()
    {
        return Task.Factory.StartNew(() =>
            {
                while (_currentLocation == null && !LocationRetrievalFailed)
                {
                }
                return _currentLocation;
            });
    }

    var location = await GetCurrentLocation();
    if (LocationRetrievalFailed)
    {
        if (location == null)
        {
            ReverseGeocodingRequestFailed = true;
            return;
        }
        // Show toast saying that we are using the last known location
    }
    Address = await GooglePlaceApiClient.ReverseGeocoding(location);
Run Code Online (Sandbox Code Playgroud)

And*_* N. 15

你试过IMvxMainThreadDispatcher吗?

var dispatcher = Mvx.Resolve<IMvxMainThreadDispatcher>();
dispatcher.RequestMainThreadAction(()=> { .... });
Run Code Online (Sandbox Code Playgroud)

详细了解实施情况:

https://github.com/MvvmCross/MvvmCross/search?q=IMvxMainThreadDispatcher&type=Code

通常我认为你不需要这个.

由于您从主线程启动异步处理,因此异步操作应返回主线程.

你能举例说明你正在做的异步代码吗?


Cla*_*edi 2

该方法RequestMainThreadAction现已过时。今天你必须做的

var dispatcher = Mvx.Resolve<IMvxMainThreadAsyncDispatcher>();
await dispatcher.ExecuteOnMainThreadAsync(()=> { .... });
Run Code Online (Sandbox Code Playgroud)