I have a button click event and inside I do a lot of work.
While I am doing this work (not from the UI project) I want to send messages to the UI to display to the user.
I am doing something like:
void Button_Click(object sender, EventArgs e)
{
DoMyWork(SendMessage);
{
public void SendMessage(string message)
{
TextBox1.Text = message + "\n";
}
and inside DoMyWork which is in another assembly i can call SendMessage which writes to the textbox. The messages will only display though when DoMyWork is complete.
How can I update TextBox1.Text on the fly without putting DoMyWork on a BackGround thread or do i have to put it on a BackGround thread? I do actually want to block the user from doing anything while DoMyWork is running
thanks
You really need to put long running operations on a separate thread. If you do not then the UI will become unresponsive and the user will think it has hung up. There are two common ways of getting the worker thread started.
There are two generally accepted methods for updating the UI safely with data generated by the worker thread.
Control.Invoke.The
BackgroundWorkerclass inherently uses the push method (viaControl.Invoke) to report progress when using theReportProgressmethod in conjuction with theProgressChangedevent.Creating a thread manually allows you to have better control over how the UI and worker thread interactions take place in exchange for having to wire up all the plumbing yourself.
Since I do not know the details of the long running operation nor the nature of the messages that need to be displayed I cannot say for certain direction will work best for you. Starting off with
BackgroundWorkerapproach will probably be okay.