Click here to Skip to main content
6,305,776 members and growing! (15,754 online)
Email Password   helpLost your password?
Languages » C# » Delegates and Events     Intermediate License: The Code Project Open License (CPOL)

How to call a long running method asynchronously and display a wait image on UI

By Member 2941560

This article explains how to call a long running method asynchronously and also display a wait image on UI.
C#, .NET (.NET 2.0, .NET 3.0, .NET 3.5), ASP.NET, Architect, Dev
Posted:15 Aug 2008
Updated:27 Aug 2008
Views:7,625
Bookmarked:23 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
7 votes for this article.
Popularity: 1.86 Rating: 2.20 out of 5

1
3 votes, 60.0%
2
2 votes, 40.0%
3

4

5

Introduction

This article describes how to call a long running method asynchronously on a separate thread and also display a wait image until the thread is not done executing task.

Background

There have been many situations where developers have to run a function/method/programming logic that takes substantially longer than usual. In that case it's always recommended to run it asynchronously in a separate thread and also display wait message/image to the end user. This sample application will explain how this can be achieved.

Using the code

First I have declared two delegates in class Form1. LoadDataDelegate is used to call the long running method asynchronously and it takes the key as a parameter (just to show a parameterized sample). The other one DisplayWaitDelegate is used to display/hide the wait image. It takes a boolean parameter to set whether to display or hide.

            
//declare a delegate to run the Load method in a separate thread
delegate void LoadDataDelegate(string key);
//declare a delegate to call the Display Wait method
delegate void DisplayWaitDelegate(bool boolDisplay);
        

The following code is in my Load Data Button click event. I will explain the function DisplayWait code later but this is used to display the wait image. The function "LoadData" in the Class1 takes a longer to execute so I have instantiated the LoadDataDelegate delegate and passed in this function name. Finally call BeginInvoke to start. Notice the second parameter which is a function name (which is explained later) is called when this asynchronous call / thread is compleated.

            
private void btnLoadData_Click(object sender, EventArgs e)
{
//will be calling the long running methid, so diaplay the wait image
DisplayWait(true);
string key = textBox1.Text;
Class1 objClass1 = new Class1();

//Create an instance of the Load delegate and pass in the Function Name
LoadDataDelegate delLoadData = new LoadDataDelegate(objClass1.LoadData);

//Since we want to call the Load function asynchronously on another thread, use BeginInvoke. The next
//argument is the function name being called once this thread is completed
delLoadData.BeginInvoke(key, this.LoadComplete, delLoadData);
}
        

Following is the code of LoadComplete Function. This function gets the handle for the delegate and calls the EndInvoke method to stop asynchronous call. Again the function DisplayWait is called but this time with the parameter boolean value false, which hides the wait image.

            
private void LoadComplete(IAsyncResult ar)
{
LoadDataDelegate d = (LoadDataDelegate)ar.AsyncState;

//end the Load method call
d.EndInvoke(ar);

//now when the Load is complete..remove the wait image
DisplayWait(false);

MessageBox.Show("Data Load Completed.");
}
        

Following is the code of DisplayWait Function. The pcitureBox1 control contains the wait image. The InvokeRequired call is needed to ensure this program doesn't cause any cross thread exception. Again create an instance of the DisplayWaitDelegate and pass the same Method Name "DisplayWait". Then call the Invoke method of the control (in this case the pictureBox1) and pass the delegate instance and parameters in an array of object (in this case just one parameter).

Now this will call the Function DisplayWait again and this time it will go in the else block and there I'm setting up the visibility. I'm also setting up the UseWaitCursor property at the Form level to display the hour glass when the wait image is being displayed.

            
private void DisplayWait(bool boolDisplay)
{
//this check is required to carry out the cross thread oprtation on a control which is pictureBox1 in this case.
if (pictureBox1.InvokeRequired)
{
// this is worker thread
DisplayWaitDelegate del = new DisplayWaitDelegate(DisplayWait);
pictureBox1.Invoke(del, new object[] { boolDisplay });
}
else
{
// this is UI thread 
pictureBox1.Visible = boolDisplay;
UseWaitCursor = boolDisplay;
}
}
        

Now the last but not the least the function "LoadData" in the Class1 which is nothing but Thread.Sleep(10000) to show a sample delay of 10 seconds with this application.

            
//long running method 

public void LoadData(string key) 
{

// The actual method imlementation

//just for sample delay added the sleep for 10 seconds
Thread.Sleep(10000); 
}
        

Points of Interest

This can also be extended to show a Progress Bar.

History

Version 1.0 Dated 08/22/2008

License

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

About the Author

Member 2941560


Member
I have worked extensively in microsoft technologies for over 8 years now. I have worked on some pretty big size development projects and love progamming in C#, .Net. In my spare time I love reading, blogging and spending time with family.
Occupation: Software Developer (Senior)
Company: Nu Info Systems
Location: United States United States

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 9 of 9 (Total in Forum: 9) (Refresh)FirstPrevNext
Questioncan I use this in web application? Pinmembermariagp10:33 17 Oct '08  
GeneralUse BackGroundWorker PinmemberAbhijit Jana18:41 27 Aug '08  
RantRe: Use BackGroundWorker PinmemberIlíon2:21 28 Aug '08  
GeneralBackgroundThread PinmemberItay Sagui7:41 27 Aug '08  
GeneralRe: BackgroundThread Pinmembermarco_br8:12 27 Aug '08  
GeneralRe: BackgroundThread PinmemberCIDev10:48 27 Aug '08  
RantBackgroundThread ... useful if you have it PinmemberIlíon2:20 28 Aug '08  
GeneralRe: BackgroundThread ... useful if you have it PinmemberRoberto Collina4:20 28 Aug '08  
GeneralRe: BackgroundThread ... useful if you have it PinmemberIlíon5:16 28 Aug '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 27 Aug 2008
Editor:
Copyright 2008 by Member 2941560
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project