Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Multithreading

I want to implement such logic in my asp-net-mvc application:

user clicks a button ->

server executes some time-consuming logic in ~15 threads (i get data from really slow independent sources) ->

when all work is done, server merges the results and passes it back to user

The other day i've seen an article which explained why creating new Threads in asp-net application is highly not recommended, and ThreadPool is the one that should be used. What are best practices for mvc in this case? Why shouldnt i create my threads, backgroundworkers, tasks, whatever by myself and use threadpool? The Application will be hosted on a public server, if it matters.

like image 223
Ilya Smagin Avatar asked Sep 25 '10 17:09

Ilya Smagin


Video Answer


2 Answers

This seems like a really good place for using the new AsycController in ASP.NET MVC 2. It is really easy to use and lets you run queries against multiple independent sources without blocking request threads.

MSDN has a great example where they are querying a news service, a weather service, and a sports service.

You can see in the original code that they are querying each source sequentially, but in the final version, all the tasks run in parallel and control returns to the controller when they are all completed:

public void IndexAsync(string city)
{
    AsyncManager.OutstandingOperations.Increment(3);

    NewsService newsService = new NewsService();
    newsService.GetHeadlinesCompleted += (sender, e) =>
    {
        AsyncManager.Parameters["headlines"] = e.Value;
        AsyncManager.OutstandingOperations.Decrement();
    };
    newsService.GetHeadlinesAsync();

    SportsService sportsService = new SportsService();
    sportsService.GetScoresCompleted += (sender, e) =>
    {
        AsyncManager.Parameters["scores"] = e.Value;
        AsyncManager.OutstandingOperations.Decrement();
    };
    sportsService.GetScoresAsync();

    WeatherService weatherService = new WeatherService();
    weatherService.GetForecastCompleted += (sender, e) =>
    {
        AsyncManager.Parameters["forecast"] = e.Value;
        AsyncManager.OutstandingOperations.Decrement();
    };
    weatherService.GetForecastAsync();
}

public ActionResult IndexCompleted(string[] headlines, string[] scores, string[] forecast)
{
    return View("Common", new PortalViewModel  {
        NewsHeadlines = headlines,
        SportsScores = scores,
        Weather = forecast
    });
}
like image 186
Rohan Singh Avatar answered Sep 22 '22 21:09

Rohan Singh


Yes JQuery and some AJAX will do it most properly. Load the Page, then send ~15 separate Ajax queries back to the Server and let them finish asynchronously. This way you can let the web-server handle Threading (which is does well) and concentrate on displaying either a ticker or a virtual progress bar to the user while waiting.

like image 34
Rune Baess Avatar answered Sep 22 '22 21:09

Rune Baess