How can I return a response from a WCF call and then do more work?
I have a synchronous web service call that returns a message. I need to quickly return a message that says the order has been received. Then I need to spend a couple of minutes processing the order, but I can't block the service call for that long. So how can I return from a web service and then do a few more things? I am guessing that I need to deploy some other thread or something before I return, but I am not sure about the best approach.
string ProcessOrder(Order order)
{
if(order.IsValid)
{
return "Great!";
//Then I need to process the order
}
}
a source to share
You can start your large body of work in a separate 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
}
a source to share
Is the work you are doing "important"? I guess it is. You can use a thread, but you should be fine with the possibility that your work could be interrupted if the machine reboots or the asp.net worker process possibly restarts. This will likely result in the job not getting done, even if you already told the client that you accepted it. This may or may not depend on your use case.
I would consider taking the work item you received from a synchronous service request and putting it on a persistent queue. An easy way to do this is to use the MSMQ transactional queue. Your synchronous service is queuing a work request, and you have multiple worker threads pulling work requests from the queue. Wrap your read queue and do the transaction and don't commit the transaction until the job is done. If you start the machine or handle it in the middle of a request, it will restart automatically the next time you start it.
a source to share