Friday, May 29, 2009

C# - UI Cross Thread

If you use a UI thread to perform lengthy process, you will experience UI "hang" and you will not be able to do anything else (even closing the UI)

To fix that, you will have to start another thread to perform these lengthy process.

//doLengthyProcess is a method that perform your process
Thread newThread = new Thread(new ThreadStart(doLengthyProcess));

// Start the thread

But now, if you update UI component at this newThread, you will encounter Croess Thread Exception. The way to fix cross thread issue is delegate. Some steps are

1. You have to create a UI method that update your UI components.
2. Create a Delegate callback to perform UI thread callback
3. Check for InvokeRequire of your UI component
4. If invoke required, use delegate callback to wake up UI thread to perform UI action

//delegate to clear textfield
public delegate void ClearText();

//method to clear text. It check for Cross Thread too
private void clearText() {
if (myText.InvokeRequired){
this.Invoke(new ClearText(clearText));
myText.Text = "";

1 comment:

Tomcat - removing server info

Below are the steps to remove Tomcat Server Information 1. Make sure Tomcat is not running 2. Navigate to "Tomcat Installation"...