1

I have a Window that only has one frame to show the different pages that my application has.

When a Page loads, it initializes several threads that deal with different elements of the UI. When I change the page with frame.Navigate(new NextPage()) I abort those threads, as it doesn't make sense to keep them running when the page is not in the foreground.

The problem comes when I make frame.GoBack(), since I have no way to relaunch those treads on the page because no code is executed when I return to the page.

There is something similar to the OnPause, OnStart, OnStop method of Android but for WPF and pages?

Something like the following:

public MainPage()
{
    InitializeComponent();
    var thread = new Thread(() => Code());
    thread.Start();
}

public Code()
{
    // Do Stuff
}

public Continue()
{
    thread.abort()
    frame.Navigate(new NextPage()) 
}

public OnPageReloaded()
{
    thread.start()
}
Lechucico
  • 1,914
  • 7
  • 27
  • 60
  • don't abort the threads and don't dispose the page – Bizhan Feb 05 '20 at 09:00
  • Some of these threads are for going back after a timeout. If I don't abort these threads, it will call frame.GoBack() when I'm on another page. – Lechucico Feb 05 '20 at 09:01
  • so implement a logic to prevent them from calling GoBack. or abort some of them and pause the rest – Bizhan Feb 05 '20 at 09:09

1 Answers1

1

You should look into the Task Parallel Library (TPL) and create tasks instead of threads. Calling Abort() on a thread is bad practice.

As to your actual question, you could initialize your work in the Loaded event handler of the Page instead of doing it in the constructor:

public partial class Page1 : Page
{
    public Page1()
    {
        InitializeComponent();
        Loaded += Page1_Loaded;
    }

    private void Page1_Loaded(object sender, RoutedEventArgs e)
    {
        //start your tasks here...
    }
}

The Loaded event will be invoked each time your Page instance is being navigated to. There is also an Unloaded event that you can use to do cleanup.

mm8
  • 163,881
  • 10
  • 57
  • 88