WPF Best practice for async property

前端 未结 2 1219
野性不改
野性不改 2021-01-27 03:37

Let\'s suppose I have a long running Web API call (async method) which returns a string.

Is there a best practice between those 2 solutions to display the result in a WP

相关标签:
2条回答
  • 2021-01-27 04:07

    In both cases, you're not catching any errors that might happen while trying to call the Web API. You might want to log it to a file and/or show an error message to the user.

    In that case, await makes it easy - you can just use try/catch:

    public MyConstructor()
    {
        try
        {
            Task task = SetAsyncPropertyA();
        }
        catch (Exception e)
        {
            // log the error or show a message
        }
    }
    
    private async Task SetAsyncPropertyA()
    {
        this.AsyncPropertyA = await GetAsyncProperty().ConfigureAwait(false);
    }
    

    You could also move the try/catch to the async method. In that case, since there's no chance of an error escaping from it, you could make it async void. Sometimes this is necessary for event handlers (at least in Windows Forms - not sure about WPF.)

    public MyConstructor()
    {
        SetAsyncPropertyA();
    }
    
    private async void SetAsyncPropertyA()
    {
        try
        {
            this.AsyncPropertyA = await GetAsyncProperty().ConfigureAwait(false);
        }
        catch (Exception e)
        {
            // log the error or show a message
        }
    }
    
    0 讨论(0)
  • 2021-01-27 04:26

    You should try to use a good framework for that, which already inveted that wheel.

    Take a look at ReactiveUI command sample:

    LoadTweetsCommand = ReactiveCommand.CreateAsyncTask(() => LoadTweets())
    
    LoadTweetsCommand.ToProperty(this, x => x.TheTweets, out theTweets);
    LoadTweetsCommand.ThrownExceptions.Subscribe(ex => /* handle exception here */);
    

    Those extensions work on IObservable, which on itself is very powerfull tool:

    Observable.FromAsync(async () =>
                {
                    await Task.Delay(100);
                    return 5;
                }).ToProperty(x => )
    
    0 讨论(0)
提交回复
热议问题