Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Async | CallBack

Status
Not open for further replies.

ralphtrent

Programmer
Jun 2, 2003
958
US
Hi
I am trying to understand how to send out work on one thread and then get the response when thread is complete. With all the books and internet sample code, I can not get the grasp of it. Can some one please post an example that will show me how to do this?

Thanks
 
Let's assume you have a method public void DoWork() that is doing all the processing you need.

1. Create a delegate: public delegte void WorkDelegate;. You will be using this delegate in order to asynchronously execute the "DoWork" method.
2. Create a callback method: protected void WorkCallback( IAsyncResult aResult). This is the method that will be called when "DoWork" will complete.
3. Run your code asynchronously!
Code:
WorkDelegate myWorkDelegate = new WorkDelegate( this.DoWork); //create a delegate instance
myWorkDelegate.BeginInvoke( new AsyncCallback( WorkCallback), myWorkDelegate); //that's it. your code (within the "DoWork" method) is now running asynchronously inside .NET thread pool)

4. How WorkCallback must look like:
Code:
protected void WorkCallback( IAsyncResult aResult)
{
   WorkDelegate aDelegate = (aResult as AsyncResult).AsyncDelegate as WorkDelegate;
   try
   {
      aDelegate.EndInvoke();//cleanup & stuff
      //Do any additional processing if you need...
   }
   catch( /* bla bla*/)
   {
      //any exception that occurs during the execution of DoWork is catched here!
   }
}

So, indirectly you use one of .NET threadpool threads in order to execute the code you need. You get notified when the execution has finished because the callback method is called. Remember that aDelegate.EndInvoke(); MUST be called. EndInvoke performs cleanup and also returns any value that DoWork might return (if its return type was not void). Also, EndInvoke includes any ref and out parameters DoWork might have (but in my example it has none)
 
Thanks for that info, what do I need to do to tell my main thread, that the async thread is complete?
 
Maybe if I explain my goal, you will have a better understand of what I mean.

I have a web page. In the web page I call 4 methods of a custom class. The method may take about 6-8 seconds to do its work (query a database). so I have a loading time of about 24-32 seconds at least. What I would like to do is have each of the request go at once and then allow me to display the results when all the request come back. Is that possible?

Thanks
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top