Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting data in background/async task what is the best way?

I have an very quick/lightweight mvc action, that is requested very often and I need to maintain minimal response time under heavy load.

What i need to do, is from time to time depending on conditions to insert small amount of data to sql server (log unique id for statistics, for ~1-5% of queries).

I don't need inserted data for response and if I loose some of it because application restart or smth, I'll survive.

I imagine that I could queue somehow inserting and do it in background, may be even do some kind of buffering - like wait till queue collects 100 of inserts and then make them in one pass.

I'm pretty sure, that somebody must have done/seen such implementation before, there's no need to reinvent wheel, so if somebody could point to right direction, I would be thankful.

like image 536
Giedrius Avatar asked Oct 17 '11 07:10

Giedrius


People also ask

What are some background processes that need to be performed using async?

An AsyncTask streamlines the following common background process: Pre - Execute code on the UI thread before starting a task (e.g show ProgressBar) Task - Run a background task on a thread given certain inputs (e.g fetch data) Updates - Display progress updates during the task (optional)

How does async improve performance?

Asynchronous programming can in some cases help with performance by parallelizing a task. But, that is not its main benefit in day to day development. Instead, the main benefit comes from making our code more scalable. The scalability feature of a system relates to how it handles a growing amount of work.

What is the benefit of using async?

A significant benefit of the async/await pattern in languages that support it is that asynchronous, non-blocking code can be written, with minimal overhead, and looking almost like traditional synchronous, blocking code.

How do I create async tasks?

To start an AsyncTask the following snippet must be present in the MainActivity class : MyTask myTask = new MyTask(); myTask. execute(); In the above snippet we've used a sample classname that extends AsyncTask and execute method is used to start the background thread.


1 Answers

You could trigger a background task from your controller action that will do the insertion (fire and forget):

public ActionResult Insert(SomeViewModel model)
{
    Task.Factory.StartNew(() =>
    {
        // do the inserts
    });
    return View();
}

Be aware though that IIS could recycle the application at any time which would kill any running tasks.

like image 66
Darin Dimitrov Avatar answered Sep 28 '22 01:09

Darin Dimitrov