In my WPF window, I am uploading a large Excel file to internal database. I want to show the update process like which sheet it is reading etc in the text box below.
- I tried writing text in text box/ updating label content but it just holds in freeze till operation is over. For both textbox and label only first item gets updated and holds still till last item.
- I tried using another thread but since wpf runs on single thread, it doesnt allow the new thread to take control of wpf window items
Any suggestions ?
CodePudding user response:
You should NEVER use the UI thread for other things, if you want to program good software! Things like uploading, you put in a thread or in a task, which of course has NO access to the UI elements, but there is a dispatcher for that.
private void CopyTask()
{
Task.Run(() =>
{
//here comes in your task that takes a long time.
//But you can still move your window in the time.
UpdateText("10$");
Thread.Sleep(1000);
UpdateText("20$");
Thread.Sleep(1000);
UpdateText("50$");
Thread.Sleep(1000);
UpdateText("100$");
Thread.Sleep(1000);
});
}
private void UpdateText(string Value)
{
//checks if it has access, if not then it goes through the dispatcher,
//which can call the method with the necessary rights
if (!Txtbox.CheckAccess())
Txtbox.Dispatcher.BeginInvoke(DispatcherPriority.Normal, () =>
{
UpdateText(Value);
});
else
Txtbox.Text = Value;
}
But I would recommend you to learn first what WPF, Threads and Dispatcher are.