简体   繁体   中英

Running a Task from App.xaml.cs on the Windows Phone 8

I have the following task i would love to initialize once the app is running, and just populate a value in my App.xaml.cs

public partial class App : Application
{
    public bool ProcessedTask = false;
    public List<Item> Items = new List<Item>();

    public App()
    {
         ...

        // Standard XAML initialization
        InitializeComponent();

        // NOW HERE I WOULD LIKE TO INVOKE MY TASK
    }

    public async Task<string> RequestDataTask()
    {
        HttpClient client = new HttpClient();

        Task<string> getStringRequests = client.GetStringAsync("http://test.com/get/");

        ItemsRootObject responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject<ItemsRootObject>(getStringRequests);

        foreach (Item item in responseObject.rows)
        {
           Items.Add(item);
        }

        ProcessedTask = true;

        string Message = "Processed Task";

        return Message;

    }
}

public class ItemsRootObject
{
    public List<Item> rows { get; set; }
    public bool success { get; set; }
    public int code { get; set; }
    public string msg { get; set; }
}

public class Item 
{
    public string value { get; set; }
}

I already know the JSON return and objects are there correctly (works in a regular call), but i don't know (understand) how to invoke my task while keeping the phone app going (load MainPage.xaml).

Anyone can tell how i get my task started asynchronously?

You can use async and await where you need to call the task.

private async void yourFunction(object sender, RoutedEventArgs e)
{
    string result = await RequestDataTask();
}

http://msdn.microsoft.com/it-it/library/hh191443.aspx

But if you want to call an async method inside a constructor use something like this:

public partial class App
{
  private readonly Task _initializingTask;

  public App()
  {
    _initializingTask = Init();
  }

  private async Task Init()
  {
    /*
    Initialization that you need with await/async stuff allowed
    */
    string result = await RequestDataTask();
  }
}

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