2014-02-12 20 views
3

我正在使用MVVMCross與我的跨平臺Windows Phone和Android應用程序。在覈心項目的主視圖模型中,我正在做一些使用TPL的後臺工作,並且我想確保在回調中,當我更改視圖模型的屬性(這將觸發UI更改)時,運行代碼UI線程,我該如何實現?在MVVMCross中查看模型的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); 

回答

12

你嘗試IMvxMainThreadDispatcher?

var dispatcher = Mvx.Resolve<IMvxMainThreadDispatcher>(); 
dispatcher.RequestMainThreadAction(()=> { .... }); 

查看更多關於執行:

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

通常我不認爲你需要這個雖然。

由於您從主線程開始異步處理,因此異步操作應返回主線程。

你可以舉一個你正在做的異步代碼的例子嗎?

+0

也看到很多問題在這裏 - 像http://stackoverflow.com/questions/16142629/mvvmcross-calling-web-service-from-view-model/16142789#16142789 – Stuart

+0

我添加了一些代碼示例。另外我想知道是否可以安全地修改除主UI線程以外的線程中的ViewModel屬性? – imgen

+0

當你說「自從你開始從主線程的異步處理以來,異步操作應該返回到主線程。」,你的意思是C#5.0的異步/等待或只是任務?或兩者?我想知道如果我將ContinueWith回調附加到任務,它是在調用者線程還是任務線程上? – imgen