Home > Enterprise >  Get data in parallel with MVC 3, .NET 4.5 and EF 6
Get data in parallel with MVC 3, .NET 4.5 and EF 6

Time:09-22

I'm working on MVC 3 project with .NET 4.5 and Entity Framework 6. My goal is to execute several data requests with Entity framework in parallel.

I know with MVC 3, async await keywords are not supported, but Tasks are partially supported.

My question is:

How can I get data in parallel with Entity Framework in a controller? With MVC 5 I must use ".ToListAsync()" and "await" in my repository and in my controller, but is not possible with MVC 3.

I think the best solution is:

[HttpPost]
public ActionResult Test()
{
    var tasks = new List<Task>();

    var myRepository = new MyRepository();
    List<Object1> object1List = null;
    tasks.Add(Task<List<Object1>>.Factory.StartNew(() => object1List = myRepository.GetAll1()));

    List<Object2> object2List = null;
    tasks.Add(Task<List<Object2>>.Factory.StartNew(() => object2List = myRepository.GetAll2()));

    Task.WaitAll(tasks.ToArray());
}

public class MyRepository
{
    /// <summary>
    ///     This query takes ~90ms
    /// </summary>
    public List<Object1> GetAll1()
    {
        using (var context = new MyContext())
        {
            return context.MyTable1.ToList();
        }
    }

    /// <summary>
    ///     This query takes more time (~400ms)
    /// </summary>
    public List<Object2> GetAll2()
    {
        using (var context = new MyContext())
        {
            return context.MyTable2.Join(...).Where(...).OrderBy(...).ThenBy(...).ToList();
        }
    }
}

Is this really the right solution? Thanks!

CodePudding user response:

Check this answer here. Basically MVC 3 does not support async await but you should not use task factory.

You need to use the Task Paraller library for MVC 3.

Basically, what it says is that you should go with

tasks.Add(Task.Run(() => object1List = myRepository.GetAll1()));
  • Related