Annamalai S
Annamalai S

Reputation: 127

Async await in mvvm silverlight 4

In my silverlight mvvm application i am using wcf service to fill listbox which is taking time to load so i need to use async and await in that. how can i use it in the bellow code.

my code in view model:

    private void GetLanguage()
    {
        ServiceAgent.GetLanguage((s, e) =>Language = e.Result);
    }

my code in service agent

    public void GetLanguage(EventHandler<languageCompletedEventArgs> callback)
    {
        _Proxy.languageCompleted += callback;
        _Proxy.languageAsync();
    }

Can anyone help me

Upvotes: 1

Views: 1836

Answers (2)

Toni Petrina
Toni Petrina

Reputation: 7122

You must use TaskCompletionSource to convert EAP (event asynchronous model) to TAP (task asynchronous model). First, add new method to your ServiceAgent (you can create this even as an extension method):

public Task<string> GetLanguageAsync(EventHandler<languageCompletedEventArgs> callback)
{
    var tcs = new TaskCompletionSource<string>();
    EventHandler<languageCompletedEventArgs> callback;
    callback = (sender, e) =>
    {
        _Proxy.languageCompleted -= callback;
        tcs.TrySetResult(e.Result);
    };

    _Proxy.languageCompleted += callback;
    _Proxy.languageAsync();

    return tcs.Task;
}

TCS will create a task which you can await then. By using the existing model, it will bridge the gap and make it consumable with async/await. You can now consume it in the view model:

private void GetLanguage()
{
    Language = await ServiceAgent.GetLanguageAsync();
}

Upvotes: 4

Morten Frederiksen
Morten Frederiksen

Reputation: 5165

You can achieve using async and await in Silverlight 5 (or .NET 4) by using this library: AsyncTargetingPack. AsyncTargetingPack is on NuGet.

For a complete walkthrough, read this excellent article:

Using async and await in Silverlight 5 and .NET 4 in Visual Studio 11 with the async targeting pack

Upvotes: 0

Related Questions