I have code like below and i am facing UI Hung issue, there is no direct way to reproduce it. its occurring randomly 1 out 10 times. I am not able to identify what is causing issue.
I have below button click code which will show a child window:-
private void processCart_Click(object sender, RoutedEventArgs e)
{
// processcart is Child Window Like Dialog To Open on Top Of Main Window
processcart = new ProcessCart();
processcart.Closed += ProcessCart_OnClosed;
// Disable Parent Window
this.Dispatcher.Invoke(new Action(() =>
{
try
{
this.IsEnabled = false;
}
catch (Exception ex)
{ }
}));
processcart.Owner = Window.GetWindow(this);
// Openning Child Window
processcart.Show();
}
private void ProcessCart_OnClosed(object sender, EventArgs e)
{
// On Child Window Close Doing some UI Update on Main Window
totalChangeAmount.Dispatcher.Invoke(new Action(() =>
{
try
{
totalChangeAmount.Text = XFuelMath.roundingTwo(cart.ChangeTotal) + "";
}
catch
{ }
}));
// Starting Background Worker Thread for Database operation.
if (!bgwTransaction.IsBusy)
{
bgwTransaction.RunWorkerAsync(cart);
}
}
private void bgwTransaction_DoWork(object sender, DoWorkEventArgs e)
{
// Doing some database operation but no UI Operation
// I dont know if i can call task inside background worker.
Task.Run(() => DeleteCurrentTicketDataFromDB(dataList, false));
// Calling another background worker inside it
if (!bgwPrintRecipt.IsBusy)
{
bgwPrintRecipt.RunWorkerAsync();
}
}
private void bgwPrintRecipt_DoWork(object sender, DoWorkEventArgs e)
{
// Sending Data to printer
}
private void bgwPrintRecipt_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// No Ui Operation Here
}
private void bgwTransaction_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Some UI Operation
totalSurcharge.Dispatcher.Invoke(() =>
{
totalSurcharge.Text = "0";
});
saleNumber.Dispatcher.Invoke(() => { });
saleDataGrid.Dispatcher.Invoke(new Action(() =>
{
try
{
saleDataGrid.ItemsSource = currentSharedTicketCollection;
saleDataGrid.Items.Refresh();
if (isautoscroll && item!=null)
{
saleDataGrid.ScrollIntoView(item, saleDataGrid.Columns[0]);
saleDataGrid.SelectedItem = item;
}
}
}));
// Enable the parent window Again
this.Dispatcher.Invoke(new Action(() =>
{
try
{
this.IsEnabled = true;
}
catch (Exception ex)
{ }
}));
}
I am not sure if i am calling BackgroundWorker inside do DoWork and RunWorkerCompleted.
Please guide me what i need to change in this code?