C# - How to set the property to Ui Thread

-5

I'm getting an error (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD)).
What should be the problem here, my senior dev said I need to set it to the UI Thread, here's my code:

private bool CanPrintReceipt() {
    return _receipt != null && !IsBusy;
}

private async void PrintReceipt() {
    IsBusy = true;
    try {
        await _printReceiptInteractor.PrintTerminalReceiptAsync(_receipt).ConfigureAwait(false);
        Dispatcher.Dispatch(() => {
            this.Close();
        });
    } catch (Exception e) {
        _log.Error($"{nameof(PrintReceipt)}: ", e);
        await this._dialogService
            .ShowMessageOKAsync(e.Message, "Printer Error");
    } finally {
        IsBusy = false; // but when i set this to true , no error
    }
}

I'm having error in my other class,

    public void RaisePropertyChanged([CallerMemberName]string propertyName = null)
    {
        if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            return;

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); //here it shows that error
    }

What do you guys think the problem is? There is no RunAsync, I saw that's the other solution
Thanks,
Nico

c#
uwp
asked on Stack Overflow Aug 5, 2016 by Reaper • edited Aug 5, 2016 by iberbeu

1 Answer

2

The problem is with .ConfigureAwait(false).

What it does is sets continueOnCapturedContext to false, which means it not necessary will be the same thread to continue evaluate the function after awit that invoked the asynchronous function.

So in your case you don't need it, because that's exactly what you need - to restore in the same thread after it's done.

And in general, the simple rule of thumb is:

  • You use .ConfigureAwait(false) in the library code that is general purpose and does not deal with UIs
  • You don't use it otherwise.

Details: MSDN - Async/Await - Best Practices in Asynchronous Programming

answered on Stack Overflow Aug 5, 2016 by zerkms

User contributions licensed under CC BY-SA 3.0