ASP.Net Web Service: Running Code Asynchronously

I have a web service that can be divided into two main sections:

[WebMethod] MyServiceCall() { //Do stuff the client cares about //Do stuff I care about } 

What I would like to do is run this second part in another thread so that the client does not expect it: as soon as the user logic is complete, immediately send them your information, but continue to process the things I need (registration, etc. )

From a web service, the recommended way to start this second part asynchronously so that you can return your information to the user as quickly as possible? BackgroundWorker ? QueueUserWorkItem ?

+6
source share
2 answers

You might want to explore Tasks , which are new to .NET 4.0.

This allows you to run an asynchronous operation, but also gives you an easy way to see if it was done or not later.

 var task = Task.Factory.StartNew(() => DoSomeWork()); 

It will start DoSomeWork () and continue without waiting to continue with another processing. When you get to the point that you don't want to process more until your asynchronous task completes, you can call:

 task.Wait(); 

Which will wait there until the task is completed. If you want to return the result from the task, you can do this:

 var task = Task.Factory.StartNew(() => { Thread.Sleep(3000); return "dummy value"; }); Console.WriteLine(task.Result); 

Call the task.Result function before receiving the result.

Here's a tutorial on tasks in more detail: http://www.codethinked.com/net-40-and-systemthreadingtasks

+4
source

The easiest way to start a new thread is perhaps:

 new Thread(() => { /// do whatever you want here }).Start(); 

Be careful if - if the service comes in very often, you can complete the creation of many threads that block each other.

+1
source

Source: https://habr.com/ru/post/905845/


All Articles