I'm fairly new to tasks and want to implement them on my application. What I want is to do an ajax request on my client side when the page loads, to a function that calls all the catalogs that I need and returns a JSON of all the objects to my client. This function on the server side is the one I created to have multiple tasks. So I have the following questions regarding this:
- Is it a good practice to load all catalogs needed for that page and return a JSON object?
Does it actually work as multi thread if the tasks call the same instance of a class? Or is it better to create the instance inside each task?
public JsonResult GetCatalogs() { JsonResult jSonResult = new JsonResult(); try { CatalogsRepository catalogsRepository = new CatalogsRepository(); Task<IList<CustomObject1>> task1 = Task.Factory.StartNew(() => { IList<CustomObject1> resultList1 = catalogsRepository.getFirstCatalog(); return resultList1; }); Task<IList<CustomObject2>> task2 = Task.Factory.StartNew(() => { IList<CustomObject2> resultList2 = catalogsRepository.getSecondCatalog(); return resultList2; }); Task<IList<CustomObject3>> task3 = Task.Factory.StartNew(() => { IList<CustomObject3> resultList3 = catalogsRepository.getThirdCatalog(); return resultList3; }); jSonResult = Json(new { result1 = task1.Result, learningMaterialTypeList = task2.Result, contentAssociatedList = task13.Result }); jSonResult.MaxJsonLength = int.MaxValue; jSonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet; } catch (Exception ex) { log.Error(ex); return Json(new Error { messageCode = 1, message = ex.Message }); } return jSonResult; }
Or is it better to create the instance inside each task?
public JsonResult GetCatalogs() { JsonResult jSonResult = new JsonResult(); try { Task<IList<CustomObject1>> task1 = Task.Factory.StartNew(() => { CatalogsRepository catalogsRepository = new CatalogsRepository(); IList<CustomObject1> resultList1 = catalogsRepository.getFirstCatalog(); return resultList1; }); Task<IList<CustomObject2>> task2 = Task.Factory.StartNew(() => { CatalogsRepository catalogsRepository = new CatalogsRepository(); IList<CustomObject2> resultList2 = catalogsRepository.getSecondCatalog(); return resultList2; }); Task<IList<CustomObject3>> task3 = Task.Factory.StartNew(() => { CatalogsRepository catalogsRepository = new CatalogsRepository(); IList<CustomObject3> resultList3 = catalogsRepository.getThirdCatalog(); return resultList3; }); jSonResult = Json(new { result1 = task1.Result, learningMaterialTypeList = task2.Result, contentAssociatedList = task13.Result }); jSonResult.MaxJsonLength = int.MaxValue; jSonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet; } catch (Exception ex) { log.Error(ex); return Json(new Error { messageCode = 1, message = ex.Message }); } return jSonResult; }
I'm using MVC .NET 4.0 with jQuery, Thank you in advance.