简体   繁体   中英

How to return data using await function in C# windows phone 8?

I'm new to C#. I I've a problem related to async methods and await function in C# windows phone 8.0.

I've this http request and can get response. This is working fine and There is no issue...

public async static Task<List<MyAccountData>> GetBalance()
{
       HttpClient = new HttpClient();
       string response = await client.GetStringAsync("http://xxxx/xxx/xxx");

       List<MyAccountData> data = JsonConvert.DeserializeObject<List<MyAccountData>>(response);

       return data;
}

I've another class call MainModel

public class MainModel
{
       public void LoadData()
       {

       }
}

So My problem is, I want to call that GetBalance method with in MainModel class and parse data to LoadData method(simply want 2 access Data with in LoadData method). LoadData method can't change return type or can't use async . So how is this possible?

There is no difference to use async await in Windows Phone 8 dev:

public class MainModel
{
    public async void LoadData()
    {
        var data = await Foo.GetBalance();
    }
}

Depends on whether you want LoadData to be synchronous (not returning until all the data has been streamed in over HTTP, and locking up the UI until then), or to begin the process and return immediately. If you can't change LoadData to async, then those are your only two options.

If you want LoadData to be synchronous:

public void LoadData() {
    var task = GetBalance();
    var result = task.Result; // will lock up the UI until the HTTP request returns
    // now do something with result
}

If you want it to start a background process and return immediately, but for some reason don't want to mark LoadData as async :

public void LoadData() {
    BeginLoadData();
}
private async void BeginLoadData() {
    var result = await GetBalance();
    // now do something with result
}

Though really, there's no reason not to go ahead and make LoadData async. async void does not force you to change the callers in any way (unlike Async<Task<T>> ), and it's assignment-compatible with plain old non-async delegates:

public async void LoadData() {
    var result = await GetBalance();
    // now do something with result
}
// ...
LoadData(); // works just fine
Action myAction = LoadData; // works just fine

As you are working on asynchronus operations you need to wait until the operation is completed.The return type async/await method is always Task(TResult) , to access the result of the async/await you need to use Result Property.The get accessor of Result property ensures that the asynchronous operation is complete before returning.

    public void LoadData()
    {
        var  data = GetBalance().Result;
    }

If you want a responsive UI - ie, one that has a chance of being accepted in the store - then blocking on the async operation is not an option .

Instead, you have to think a bit about how you want your UI to look while the operation is in progress. And while you're thinking about that, also think about how you would want your UI to respond if the operation errors out.

Then you can code up a solution. It's possible to do this with async void , if you catch all exceptions and handle them cleanly:

public async void LoadData()
{
  try
  {
    ... // Set up "loading" UI state.
    var balance = await GetBalanceAsync();

    ... // Set up "normal" UI state.
    Balance = balance;
  }
  catch
  {
    ... // Set up "error" UI state.
  }
}

However, I prefer to use a type I created called NotifyTaskCompletion , which is a data-bindable wrapper for Task<T> (described in my MSDN article ). Using NotifyTaskCompletion , the LoadData becomes much simpler:

public void LoadData()
{
  GetBalanceOperation = new NotifyTaskCompletion<Balance>(GetBalanceAsync());
}

public NotifyTaskCompletion<Balance> GetBalanceOperation // Raises INotifyPropertyChanged when set

Then your UI can data-bind to properties on NotifyTaskCompletion<T> , such as IsNotCompleted (for the "loading" state), IsSuccessfullyCompleted and Result (for the "normal" state), and IsFaulted and ErrorMessage (for the "error" state).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM