Click here to Skip to main content
14,970,515 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I am creating an windows based application which download the data from server.
I am using the background thread which is created on different class to perform these download operation.And I want to continuously show the download status on rich textbox i.e on main thread.But i am unable to do this,get an Cross-thread operation not valid.
Please help me to resolve this problem.
Posted

For updating the text, use a public or internal method in Form1. Check the InvokeRequired property. If it is true, call this.Invoke on the same function. E.g.
C#
public void UpdateText(string newText)
{
    if (InvokeRequired)
    {
        this.Invoke(new AFStringDelegate(UpdateText), newText);
        return;
    }
    textbox.Text = newText;
}

The delegate is available in Microsoft's Application Framework. You can also declare it:
C#
public delegate void AFStringDelegate(string s);

And now call the UpdateText method from your background thread.
   
Comments
Member 8041630 26-Sep-12 4:57am
   
Hi,
I am creating an windows based application which download the data from server.
I am using the background thread which is created on different class to perform these download operation.And I want to continuously show the download status on rich textbox i.e on main thread.But i am unable to do this,get an Cross-thread operation not valid.
Please help me to resolve this problem.


method on Form1.cs

public void UpdateRichText(string Text)
{
SetRichText(Text);
}

public delegate void SetRichTextTextDelegate(string text);
public void SetRichText(object number)
{
if (InvokeRequired)
{
this.BeginInvoke(new SetRichTextTextDelegate(SetRichText), text);
return;
}

richTextBox1.Text += number.ToString() + "\n";
}
private void button3_Click_1(object sender, EventArgs e)
{
demo d = new demo();
d.display();
}

methods on demo.cs

Form1 f = new Form1();
public void display()
{
Thread t = new Thread(new ThreadStart(call));
t.Start();
}


public void call()
{
//when i call this method every time if(InvokeRequired) is false.
f.UpdateRichText("Called from Thread");
}
You could use a Background worker and then use the ProgressChanged event which is handled in the main thread. See this sample:
C#
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
   //Tasks executed in separate thread
   backgroundWorker1.WorkerReportsProgress = true;
   backgroundWorker1.ReportProgress(1);
   Thread.Sleep(500);
   backgroundWorker1.ReportProgress(2);
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
   //event handler in main thread - update GUI here
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900