views:

117

answers:

4

I have a synchronous web service call that returns a message. I need to quickly return a message that basically says that order was received. I then need to spend a couple of minutes processing the order, but cannot block the service call for that long. So how can I return from the web service, and then do some more stuff? I'm guessing I need to fork some other thread or something before I return, but I'm not sure of the best approach.

string ProcessOrder(Order order)
{
  if(order.IsValid)
  {
      return "Great!";
      //Then I need to process the order
  }
}
+3  A: 

You can open a new thread and have it do what you need, while you're main thread returns great.

string ProcessOrder(Order order)
{
  if(order.IsValid)
  {
            //Starts a new thread
            ThreadPool.QueueUserWorkItem(th =>
                {
                    //Process Order here

                });

      return "Great!";
  }
}
Noah
+3  A: 

You could start your big amount of work in a seperate thread

public string ProcessOrder(Order order)
{
   if(order.IsValid)
   {
        System.Threading.ParameterizedThreadStart pts = new System.Threading.ParameterizedThreadStart(DoHardWork);

        System.Threading.Thread t = new System.Threading.Thread(pts);
        t.Start(order);

        return "Great!!!";
   }
}

public void DoHardWork(object order)
{
//Stuff Goes Here
}
Eoin Campbell
+1  A: 

Is the work you're doing "important?" I assume it is. You could use a thread, but you'll have to be ok with the possibility that your work might get interrupted if the machine restarts or possibly if the asp.net worker process recycles. This would likely lead to the work not getting done even though you already told the client you had accepted it. This might be or not depending on your use case.

I would consider taking the work item you receive from the synchronous service request and putting it in a persistent queue. An easy way to do this is to use a transational MSMQ queue. Your synchronous service puts the work request in the queue and you have a few worker threads pulling work requests out of the queue. Wrap your queue read and the work in a transaction and don't commit the transaction until the work is completed. If you machine or process shuts down in the middle of a request, it will be restarted automatically the next time it starts up.

Erv Walter
+1  A: 

You could also look at utilizing the PIAB (Policy Injection Application Block) to accomplish work after a method call.

MattK