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
newThread.Start();


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));
}else{
myText.Text = "";
}
}

1 comment:

Oracle - Reclaim disk space

Oracle does not release disk space even if you had delete the data or tablespace. If you have enterprise manager, you should use it to  rec...