简体   繁体   中英

WP8 async method in scheduled task

I am trying to make live tile which uses data from DownloadStringAsync method.

protected override void  OnInvoke(ScheduledTask task){
  WebClient web = new WebClient();
  web.DownloadStringAsync(new Uri("website"));
  web.DownloadStringCompleted += web_DownloadStringCompleted;
  StandardTileData data = new StandardTileData();
  ShellTile tile = ShellTile.ActiveTiles.First();
  data.BackContent = string;
  tile.Update(data);
}

void web_DownloadStringCompleted(object sender, 
                                 DownloadStringCompletedEventArgs e)
{
   string=e.result ; 
} // example

string is returning null all the time. I think it is because of async operation. Somehow if I can make it sync maybe it can work. any ideas ? thanks

You have a Race Condition Since the download operation is asynchronous, the 'string' variable (which should not compile BTW) will not necessary be updated when you will read it's value to set the BackContent.

Try this with the Async/Await keywords:

protected async override void  OnInvoke(ScheduledTask task)
{
   var web = new Webclient();
   var result = await web.DownloadStringTaskAsync(new Uri("website"));
   StandardTileData data = new StandardTileData();
   ShellTile tile = ShellTile.ActiveTiles.First();
   data.BackContent = result;
   tile.Update(data);
 }

If you can't use DownloadStringTaskAsync in your WP8 App, then try using TaskCompletionSource to accomplish the same thing, as exampled in this post .

protected async override void  OnInvoke(ScheduledTask task)
{
   var result = await DownloadStringTaskAsync (new Uri("website"));     
   StandardTileData data = new StandardTileData();
   ShellTile tile = ShellTile.ActiveTiles.First();
   data.BackContent = result;
   tile.Update(data);
 }

   public Task<string> DownloadStringTaskAsync(Uri address)
   {
      var tcs = new TaskCompletionSource<string>();
      var client = new WebClient();
      client.DownloadStringCompleted += (s, e) =>
      {
         if (e.Error == null)
         {
             tcs.SetResult(e.Result);
         }
         else
         {
             tcs.SetException(e.Error);
         }
     };

     client.DownloadStringAsync(address);

     return tcs.Task;
 }

Here are an example 1 & example 2 & example 3 from MSDN for using the Async/Await keyword with WebClient in Windows Phone 8.

Since you are using WP8, then you might need to add the Nuget package for the Async/Await keyword. just run

install-package Microsoft.Bcl.Async

In the Package Manager Console. Or use Nuget GUI to download it (search for 'async')

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