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
  }
}

      

0


a source to share


4 answers


You can open a new thread and make it do what you want it to do, while the main thread works fine.



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

                });

      return "Great!";
  }
}

      

+4


a source


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
}

      

+3


a source


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.

+1


a source


You can also see how to use PIAB (Application Application Block) to do the work after a method call.

+1


a source







All Articles