Reputation: 12294
public async Task<ActionResult> Search(string q)
{
var data = db.MediaPlanBilingInvoices.Where(m => m.IsDeleted == false);
//allthe stuff
decimal? allinvoicetotal=0;
decimal? allrototal = 0;
if (Noofrecords > 0)
{
if (WebConstants.PrintMedia)
{
var roobject = data.Where(x => x.isPrint == true).SelectMany(m => m.MediaPlanBilingInvoiceDetails);
var roobjects =roobject.Select(m=>m.RoId);
Func<decimal?> functions = new Func<decimal?>(() => roobject.Sum(m => m.MediaPlanRO.MediaPlanROPrints.Sum(qq => qq.MediaPlanPrint.Amount)));
var tasksro = await System.Threading.Tasks.Task.Factory.StartNew<decimal?>(functions);
allrototal = allrototal + tasksro.Result;
}
else if (WebConstants.ElectronicMedia)
{
var roobject = data.Where(x => x.iselectronic == true).SelectMany(m => m.MediaPlanBilingInvoiceDetails);
var roobjects =roobject.Select(m=>m.RoId);
Func<decimal?> functions = new Func<decimal?>(() => roobject.Sum(m => m.MediaPlanRO.MediaPlanROPrints.Sum(qq => qq.MediaPlanPrint.Amount)));
var tasksro = await System.Threading.Tasks.Task.Factory.StartNew<decimal?>functions);
allrototal = allrototal + tasksro ;
}
}
}
return Viewdata);
}
}
I am trying to calculate the sum of the ros in the different table for different criteria.
The problem is that when the program reachers allrototal it stops and doesn't go to the next line until it bring down the result. I want to keep it running not stop there. how can i do it?
Upvotes: 0
Views: 931
Reputation: 456437
The core problem you're having is that async
doesn't change the HTTP protocol (discussed in detail on my blog). With HTTP, you have one request and one response. If you return a response, then you can't also have something else running and then return another response later - HTTP just doesn't work that way.
So, on ASP.NET, async
allows you to free up the thread but does not complete the response. The response is not sent until the async
method is finished.
Furthermore, Task.Run
is safer than StartNew
, but neither of them should be used like this on ASP.NET because all it's doing is freeing up the request thread pool thread by using up another thread pool thread. So await Task.Run(() => functions());
is just a more expensive way of saying functions()
.
This method should just be made synchronous. There's no asynchronous work to do here. If you want your client to behave asynchronously, then your client will need to make its HTTP request asynchronously.
Upvotes: 5