What is the best way to fix the error "The method was called at an unexpected time"

First of all, I already saw this question , and I (sort of) understand why I get this exception, I would like to know that this is the best way to fix it. My code looks something like this (this is a WinRT application):

//Here is my App constructor:
public App()
{
    this.InitializeComponent();
    this.Suspending += this.OnSuspending;

    //Initializing the model
    _model = new Model();
    _model.LoadData();
}

//the LoadData method looks like this:
public async void LoadData()
{
    StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
    StorageFile file = await folder.GetFileAsync(@"Assets\Data.json");
    string data = await FileIO.ReadTextAsync(file);

    var dataList = JsonConvert.DeserializeObject<List<MyDataClass>>(data);
    // From time to time (pretty rarely, honestly) this line causes the
    // "A method was called at an unexpected time" thing:
    var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
    foreach (var item in dataList)
    {
        //do some stuff
        //<...>
        await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        () => {
            //do some stuff in the UI thread
        });                
    }
}

Obviously, the method is LoadData async voidnot the best solution. However, as you can see, I have to make some calls to asynchronous functions (to read data from a file) inside it. Now I can think of two possible solutions:

  • Change LoadDatato public async Task LoadData()and change its call in the application designer to _model.LoadData().GetAwaiter().GetResult();to start it synchronously;
  • LoadData public void LoadData() await , awaiter, . StorageFile file = folder.GetFileAsync(@"Assets\Data.json").GetAwaiter().GetResult().

, , ? , "A " ?

+4
1

- , /. , " , , ", .

, . , . ; . , .

, , , -. . . I/O . , - .

. .

?

, . , -, , . ( ), .

() "...". "..." . . , , , , ( ).

, ( @marcinax):

protected override async void OnLaunched(...)
{
  ... // Initialize UI to "Loading" state.

  _model = new Model();
  await _model.LoadData();

  ... // Update UI with data in _model.
}

( Model), , - ( ) , // Update UI.

, , (, / ), Data-binding solution, MSDN.

, "A " ?

, , .

/VM , CoreDispatcher . .

+1

Source: https://habr.com/ru/post/1612815/


All Articles