1

Is there a way to make an asynchronous call to a custom method in WP7 - WP8?

In a Windows Forms app i would simply do this:

private void btnStart_Click(object sender, EventArgs e)
{
    MyMethod();
}

private async void MyMethod()
{
    await System.Threading.Tasks.Task.Run(() => Thread.Sleep(5000));
}

However, it seems like the System.Threading.Tasks namespace is not supported in WP apps.

Then what should i do if i wished to act similarly in my WP7 - WP8 app?

1 Answer 1

3

You can install Microsoft.Bcl.Async for WP7.5 support. If you need WP7.0 support, your best bet is BackgroundWorker.

P.S. Your WinForms example would be better written as:

private async void btnStart_Click(object sender, EventArgs e)
{
    await Task.Run(() => MyMethod());
}

private void MyMethod()
{
    Thread.Sleep(5000);
}

Following these best practices:

  1. Avoid async void.
  2. Don't use Task.Run in general-purpose library methods.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for that, but i still have an issue. I wrote an asynchronous event handler for the TextBox.TextChanged event, but i get an error that states "invalid cross-thread call" when i try to do this: await TaskEx.Run(() => MyMethod()); OR await Task.Factory.StartNew(() => MyMethod()); How could i solve this?
Any UI updates need to be done on the UI thread, so they can't be within a call to Task.Run. You'll need to split up MyMethod into the "background" parts and the "UI" parts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.