Hreddy
Hreddy

Reputation:

Calling two methods Asynchronously in ASP.NET 2.0

i am trying to call two methods (one is a webservice, other is a method which helps login a user to home page) asynchronously. I dont need them to return any value, as the webservice method is just used for logging and the other has code to authenticate the user and login to home page. I am on asp.NET 2.0

I tried reading many articles who suggested using delagates etc... but i never worked on these. Can any one help me with this. Will appreciate it.

Upvotes: 0

Views: 268

Answers (2)

ObeseCoder
ObeseCoder

Reputation: 401

if you don't need to wait for results you can use the ThreadPool.QueueUserWorkItem method like Jon suggested

if you need to pass an argument into your method

string msg = "log message";
WaitCallback firstAction = delegate(object args) 
{ 
  string s = ((object[])args)[0]; 
  webService.LogAccess(s); 
};
ThreadPool.QueueUserWorkItem(firstAction, new object[] {msg});

i generally will setup another method called LogAsync to handle all of the ceremony

void LogAsync(string msg)
{
  WaitCallback firstAction = delegate(object args) 
  { 
    string s = ((object[])args)[0]; 
    webService.LogAccess(s); 
  };
  ThreadPool.QueueUserWorkItem(firstAction, new object[] {msg});
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503419

If you just want to "fire and forget" then you could just queue thread pool work items:

WaitCallback firstAction = delegate { webService.LogAccess(); };
WaitCallback secondAction = delegate { user.Login(); }

ThreadPool.QueueUserWorkItem(firstAction);
ThreadPool.QueueUserWorkItem(secondAction);

Upvotes: 2

Related Questions