www.softwareriviera.com
Software Code
    New Code     Most Interesting     Don't Miss     Our picks  
C# - section

View Article
Using threads to do actions in a Windows form
How to use threads to do actions in a Windows form
Suppose you have a form and you want to use separate threads to comunicate with the form (Windows form).

//We will use a delegate for this: first declare the delegate
public delegate void DelegateThreadResponseQueryResult(string queryResult);
public DelegateThreadResponseQueryResult _dlgDelegateQueryResult;

//Then initialize it to point to a method: you can do this on the constructor of the class (form)
_dlgDelegateQueryResult = new DelegateThreadResponseQueryResult(this.QueryResult);

//the QueryResult is the name of the method within the form. This method will be
//called when the thread wants to comunicate with the Form (see below the code).

//We will need a Mutex to synchronize the access to the shared resource which in
//our case is the destination container of the received text from the Thread: in our
//case the shared resource is the txtQueryResult Text control.
private static Mutex mutQueue = new Mutex();

public void QueryResult(string str)
{
try
{
//Signal other threads to not enter the following code until the mutQueryResult.ReleaseMutex
//instruction is encountered
mutQueryResult.WaitOne();

//HANDLE THE QUERY RESULT
if (chkAppendResultsToText.Checked)
txtQueryResult.Text += str + AppDefs.NEWLINE;
else
txtQueryResult.Text = str;
}
catch (Exception ex)
{
//HANDLE THE ERROR
AppError error = new AppError(AppDefs.ERROR_GUI_WHOIS_INFO_ERROR_RECEIVING_QUERY_RESPONSE,
AppDefs.ERROR_GUI_WHOIS_INFO_ERROR_RECEIVING_QUERY_RESPONSE_DETAILS,
ex.StackTrace + " " + ex.Message, AppDefs.ERROR_GUI_WHOIS_INFO_ERROR_RECEIVING_QUERY_RESPONSE_TEXT);
error.HandleError(true, false);
}
finally
{
//Signal other threads that they can access the shared resource(s)
mutQueryResult.ReleaseMutex();
}
}
//Suppose you have a class called: AppWhoIsAsyncOperations

//Instantiate an object and pass some parameters in the constructor
//The first parameters is 'this' and is used to know to which form to send the response back (this is of type frmMain)
whoisInfo = new AppWhoIsAsyncOperations(this, parsingDomains, checkedWhoIs);

//initialize a Thread instance like below:
Thread myThread = new Thread(new ThreadStart(whoisInfo.Run));
myThread.Start();

//Start the thread
myThread.Start();

//Then in the AppWhoIsAsyncOperations class you should use the following code, to comunicate a result to the form
_frmForm.Invoke(((frmMain)_frmForm)._dlgDelegateQueryResult, new Object[] { str });

//where _frmForm is of type frmMain and is initialized with the 'this' parameter sent in the constructor
Date: 2008-4-20    Written by: Admin A
     See all articles in this section
Copyright © 2007-2009 SoftwareRiviera.com. All rights reserved.  | Terms of use | Disclaimer | Privacy Policy |