Web service performing asynchronous call

Posted by kornelijepetak on Stack Overflow See other posts from Stack Overflow or by kornelijepetak
Published on 2010-05-31T18:31:56Z Indexed on 2010/05/31 18:33 UTC
Read the original article Hit count: 259

I have a webservice method FetchNumber() that fetches a number from a database and then returns it to the caller. But just before it returns the number to the caller, it needs to send this number to another service so instantiates and runs the BackgroundWorker whose job is to send this number to another service.

public class FetchingNumberService : System.Web.Services.WebService
{
    [WebMethod]
    public int FetchNumber() 
    {
        int value = Database.GetNumber();
        AsyncUpdateNumber async = new AsyncUpdateNumber(value);
        return value;
    }
}

public class AsyncUpdateNumber
{
    public AsyncUpdateNumber(int number)
    {
        sendingNumber = number;

        worker = new BackgroundWorker();
        worker.DoWork += asynchronousCall;
        worker.RunWorkerAsync();
    }

    private void asynchronousCall(object sender, DoWorkEventArgs e)
    {
        // Sending a number to a service (which is Synchronous) here
    }

    private int sendingNumber;
    private BackgroundWorker worker;

}

I don't want to block the web service (FetchNumber()) while sending this number to another service, because it can take a long time and the caller does not care about sending the number to another service. Caller expects this to return as soon as possible.

FetchNumber() makes the background worker and runs it, then finishes (while worker is running in the background thread). I don't need any progress report or return value from the background worker. It's more of a fire-and-forget concept.

My question is this. Since the web service object is instantiated per method call, what happens when the called method (FetchNumber() in this case) is finished, while the background worker it instatiated and ran is still running?

What happens to the background thread? When does GC collect the service object? Does this prevent the background thread from executing correctly to the end? Are there any other side-effects on the background thread?

Thanks for any input.

© Stack Overflow or respective owner

Related posts about c#

Related posts about asynchronous