LeftyX
LeftyX

Reputation: 35597

Fire Off an asynchronous thread and save data in cache

I have an ASP.NET MVC 3 (.NET 4) web application.

This app fetches data from an Oracle database and mixes some information with another Sql Database.
Many tables are joined together and lot of database reading is involved.
I have already optimized the best I could the fetching side and I don't have problems with that.
I've use caching to save information I don't need to fetch over and over.

Now I would like to build a responsive interface and my goal is to present the users the order headers filtered, and load the order lines in background.

I want to do that cause I need to manage all the lines (order lines) as a whole cause of some calculations.

What I have done so far is using jQuery to make an Ajax call to my action where I fetch the order headers and save them in a cache (System.Web.Caching.Cache).
When the Ajax call has succeeded I fire off another Ajax call to fetch the lines (and, once again, save the result in a cache).

It works quite well.

Now I was trying to figure out if I can move some of this logic from the client to the server.

When my action is called I want to fetch the order header and start a new thread - responsible of the order lines fetching - and return the result to the client.

In a test app I tried both ThreadPool.QueueUserWorkItem and Task.Factory but I want the generated thread to access my cache.

I've put together a test app and done something like this:

TEST 1

[HttpPost]
public JsonResult RunTasks01()
{
    var myCache = System.Web.HttpContext.Current.Cache;
    myCache.Remove("KEY1");

    ThreadPool.QueueUserWorkItem(o => MyFunc(1, 5000000, myCache));

    return (Json(true, JsonRequestBehavior.DenyGet));
}

TEST 2

[HttpPost]
public JsonResult RunTasks02()
{
    var myCache = System.Web.HttpContext.Current.Cache;
    myCache.Remove("KEY1");

    Task.Factory.StartNew(() =>
    {
        MyFunc(1, 5000000, myCache);
    });

    return (Json(true, JsonRequestBehavior.DenyGet));
}

MyFunc crates a list of items and save the result in a cache; pretty silly but it's just a test.

I would like to know if someone has a better solution or knows of some implications I might have access the cache in a separate thread?!

Is there anything I need to be aware of, I should avoid or I could improve ?

Thanks for your help.

Upvotes: 0

Views: 389

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

One possible issue I can see with your approach is that System.Web.HttpContext.Current might not be available in a separate thread. As this thread could run later, once the request has finished. I would recommend you using the classes in the System.Runtime.Caching namespace that was introduced in .NET 4.0 instead of the old HttpContext.Cache.

Upvotes: 1

Related Questions