简体   繁体   中英

Multithreading in Windows Phone 8.1

public MainPage()
{
    Method_1();
    Method_2();
    Method_3();
    Method_4();
    Method_5();
    Method_6();

}
  1. I am writing a Windows Phone 8.1 App (WINRT XAML). How to make these methods execute at a time from constructor? What I mean to ask is about multithreading, i want these methods to get executed sidebyside and not one after another.
  2. Does this effect loading of application? will app load fast/slow?

First off, you don't want to execute those methods in the constructor if they are long running methods. Wait until the page is loaded:

private async void Page_Loaded(object sender, RoutedEventArgs e)
{
    Task m1task = Method_1();
    Task m2task = Method_2();
    Task m3task = Method_3();
    Task all = Task.WhenAll(m1Task, m2Task, m3Task);
    await all;
}

The code will load off these operations to another thread and as long as your methods are properly implemented your UI will stay responsive (so don't use wait() for instance).

This is what a sample method could look like:

private async Task Method_1() {
    // Long running operation goes here
}

If you have some heavy computations to do, wrap them into Task.Run(() => { // Code }); It's really essential that you're aware of the concepts of asynchronous programming. You might want to read on here:

Do you have to put Task.Run in a method to make it async?

await vs Task.Wait - Deadlock?

When correctly use Task.Run and when just async-await

But seriously, you're writing that your methods are not UI related. You might be better off running those somewhere else (eg in your ViewModels or even in a background task / service).

Mark the methods as Async with return type Task.

eg. public async Task method1(){}

You won't be able to fire any UI activities from them, but they'll run outside of the main thread.

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