I have C# WPF application which reads data from database then does some work. But the problem is when I am reading data my UI doesn’t respond. I have tried Tasks and dispatcher. None of them helps. Code below is in the button_click event. Here is code:
DataSet ds;
DataTable dt = new DataTable();
Task myTask = new Task(new Action(() =>
{
//GetMyDataSet() returns DataSet
ds = GetMyDataSet();
dt = ds.Tables["MyTableName"];
}));
myTask.Start();
while (!myTask.IsCompleted)
{
System.Threading.Thread.Sleep(1000);
}
//Continue
First off, get rid of the sleep-spin, it completely defeats the purpose of using a
Tasksince it doesn’t allow the UI thread to proceed until theTaskcompletes. You don’t want that!Now your task will run in parallel with the UI thread until completion. At the end of the
Taskcode useDispatcher.BeginInvoketo update the UI. It should be ok now.