I'm trying to figure out a good way to bind the view to viewmodel properties that needs to be populated using an async method. The latest I got is using IsAsync like so.

ViewModel.cs

public class ViewModel
{
    public Task<string> Name { get; set; }

    public ViewModel()
    {
        Name = GetNameAsync();
    }

    public async Task<string> GetNameAsync()
    {
        return await Task.Run(async () =>
        {
            await Task.Delay(5000);
            return "Foo";
        });
    }
}

View.xaml

<Label Content="{Binding Name.Result, IsAsync=true}" />

It seems to work but I'm not sure if I'm using IsAsync as it's supposed to be used. The documentation doesn't state anything related to Task and there was also this comment on a stackoverflow that says IsAsync is not related to C# async.

What can go wrong with such implementation?

The cleanest way to handle this sort of "one time" async property is to use NotifyTaskCompletetion from Stephen Cleary's Nito.Asyncex library (available on Nuget).

You ViewModel would then become

public class ViewModel
{
    public INotifyTaskCompletion<string> Name { get; set; }

    public ViewModel()
    {
        Name = NotifyTaskCompletetion.Complete(GetNameAsync());
    }

    private async Task<string> GetNameAsync()
    {
        return await Task.Run(async () =>
        {
            await Task.Delay(5000);
            return "Foo";
        });
    }
}

You would then bind to Name.Result as a standard binding, no need for IsAsync.

More details here.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.