Reputation: 102
I have an .NET 5.0 WPF Application which consists of 2 threads: the UI thread and another thread that is supposed to always work in the background and get some live data from an API and save it to a MYSQL database. The UI thread then reads the database every time it gets updated and shows the data in a chart.
The problem is that I need the data getting thread to run in the background, even after closing the UI. When that happens, the thread normally saves the data to the database, but once I start the app again a new data thread starts and then there are 2 threads doing the same thing in the background.
I can't do an Environment.Exit(0);
because then the database and the chart would have some 'holes' in it, it wouldn't be complete, unless I would keep the app's UI always running minimalized, but that's not efficient and not needed.
I would want the app to somehow detect if a thread from its older instance is running and based on that either run a new thread or don't and get data saved by the still running thread from the database.
For now, the thread is run on the MainWindow Load Event It is is created this way:
Thread StockMarketThread = new Thread(new ThreadStart(updateData));
public static void updateData()
{
while(true)
{
getsetData(); //gets data from API and updates the database
Thread.Sleep(60000);
}
}
Upvotes: 0
Views: 157
Reputation: 169200
A thread lives inside a process. When the process, which in this case is your WPF application, exits all threads in it stops.
You can run your worker thread as a foreground thread to prevent the WPF application from shutting down until the background work has finished but what you probably want to do is to move the background work to a separate (backend) process that runs regardless of whether your UI app is running.
That's the only way of "getting [the] thread to run in the background, even after closing the UI [process]" and avoid "holes" in the data.
The UI should just be a consumer of the data that is produced in another process that is typiclly running on a server of some kind.
Upvotes: 4