You're using a
BackgroundWorker
to push the work onto a background thread. But you're then immediately calling
Dispatcher.Invoke
to push the work back onto the UI thread.
As a result, you're blocking the UI thread until your work completes, and keeping a background thread idle, waiting for your UI thread to finish doing the work.
You need to move as much of the work as possible into the background thread. Remove the outer
Dispatcher.Invoke
call in your
worker_DoWork
method. When you need to update the UI, use the
ReportProgress
method to pass the data back to the UI thread.
Assuming it's updating the
DetailReportFCBuySell
property that needs to happen on the UI thread, something like this should work:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
var batchFCSB = new System.Data.DataTable();
int row = 0;
if (DetailReportFCBuySell.FirstOrDefault().TotalRecords > toFetchRecords)
{
long RecordsIcrease = 1000;
batchFCSB = DetailReportFCBuySell.ToDataTable();
row = 1;
PageIndex++;
for (long k = toFetchRecords; k < DetailReportFCBuySell.FirstOrDefault().TotalRecords; k = +toFetchRecords)
{
new AlxServiceClient().Using(channel =>
{
var temp = AlyexWCFService.DL.DLTTIn.FCBuySELL(transactionName, isDetails, Convert.ToDateTime(dateEdtStartDate.EditValue).Date, Convert.ToDateTime(dtpEditEndDate.EditValue).Date, Customerid, ProductID, branchID, NoOfRecords, PageIndex - 1, isBuy);
worker.ReportProgress(0, temp);
row++;
PageIndex++;
});
toFetchRecords = toFetchRecords + RecordsIcrease;
}
}
}
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
var temp = (ObservableCollection<dlreports.fcbuyselldetail>)e.UserState;
DetailReportFCBuySell = DetailReportFCBuySell.Union(temp).ToObservableCollection();
}
NB: You'll need to set the
worker.WorkerReportsProgress
property to
true
, and wire up the
worker_ProgressChanged
method to the
worker.ProgressChanged
event.