I am creating a Winforms
application (.Net 7), which depicts statistics on charts. The source of the statistical data is MySQL query, which runs in Async Task
. After the query finishes the result datatable
is bind to the chart.
When application is started there is a main Winform, where there are buttons, which start different Winforms or multiple instances of the same Winform.
My problem is that if for example in one of the child Winforms there is a running async MySQL query and I close that Winform with the “x” and now only the main Winform is on the screen, then when query finishes there is an exception System.NullReferenceException: 'Object reference not set to an instance of an object.'
when the datatable is bind to the chart. Apparently closing the Winform is not enough to release all resources related to it (I don’t mean killing the query, which naturally continues to run on MySQL server). My expectations were that if I close the form then all is finished with it.
What is the correct approach in such situations? How can I get rid of exceptions from a Winform which was closed while its task was not finished? Having such exceptions are affecting the user experience while users are working in other forms of the same application.
Simplified example of my code is below:
Public Class Form4
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim TabCell As New DataTable
'This is the statistical table
Dim getStats As New Queries
'"Queries " is a class containing query execution functions
TabCell = Await Task().Run(Function() getStats.ExecQuery(parameters))
'This is the asynchronous run of the task for query execution.
'If the Winform is closed while this task is running...
'...there is the mentioned exception in the line below:
Chart1.DataSource = TabCell
Chart1.Series.Clear()
Chart1.Titles.Clear()
'Further code for chart definition
End Sub
End Class