I wish I knew more about threading... but can you give me an example of
how to have the thread call back on a delegate to the UI thread?
It's pretty easy thing to do when you know it well..
What you need to do is, to initialize a thread that does some stuff, then
updates the UI. You can do it many ways, but the most appropriate one is to
let the wroker thread do what it does for living, and then upon exit as long
as it has access to the calling from, it should invoke a function that
updates the user interface.
And you know, a delegate is just a handsom pointer to function.
Note that there is an "Invoke" function which is member of any windows
form/control, so that you can "Invoke" delegates on the main UI thread.
This function takes a delegate as argument and executes that delegated
function on the main thread...
So, Let's say that your function that updates the UI upon thread exit is:
public void UpdateUI()
{
BindDataGridResults();
Cursor.Current = Cursors.Default;
btnImport.Enabled = true;
}
to define a delegate that could point to this function you need the
following delegate signature:
public delegate void UpdateUIDelegate();
and how do you initialize a variable of that delegate type that points to
the mentioned function?:
UpdateUIDelegate delegatedFunc = new UpdateUIDelegate( UpdateUI );
and how the thread can safely call this function when using that delegate?:
myForm.Invoke( delegatedFunc );
We can put it all together in a simple manner:
public delegate void UpdateUIDelegate();
public class MyForm : System.Windows.Forms.Form
{
private UpdateUIDelegate _delegatedFunc = null;
//
// <Init code and other stuff snipped or unkonown>
// </>
public MyForm ()
{
}
public void TheMethodYouAreTalkingAbout()
{
//
_delegatedFunc = new UpdateUIDelegate( UpdateUI );
System.Threading.Thread worker = new System.Threading.Thread( new
ThreadStart(ThreadFunc) );
worker.Start();
// Do nothing afterwards..
}
public void ThreadFunc()
{
try
{
// Do your thrad work here, ..
// ..
// ..
}
catch(ThreadAbortException)
{
// Handle thread abort here ..
}
// Done with your work??
if ( _delegatedFunc != null )
this.Invoke( _delegatedFunc );
}
public void UpdateUI()
{
BindDataGridResults();
Cursor.Current = Cursors.Default;
btnImport.Enabled = true;
}
}
There are really cool articles on this particular subject, but I hope you
don't mess Chris Sells':
http://msdn.microsoft.com/vcsharp/using/columns/wonders/default.aspx?pull=/l
ibrary/en-us/dnforms/html/winforms06112002.asp
http://msdn.microsoft.com/vcsharp/using/columns/wonders/default.aspx?pull=/l
ibrary/en-us/dnforms/html/winforms08162002.asp
http://msdn.microsoft.com/vcsharp/using/columns/wonders/default.aspx?pull=/l
ibrary/en-us/dnforms/html/winforms01232003.asp