Billa
Billa

Reputation: 5266

Async call in MVC 4

Working on MVC 4 application. I need to do certain DB calls with out blocking the current action method execution.

public ActionResult Save(Employee e){

  bool saveStatus = EmployeeService.Save(e);

  if(saveStatus){
   AuditService.Add("Employee {0} added successfully", e.Name); //want this async
  }
  return View(e);

}

In the above code I want to make the AuditService call to async.

The moment I save employee information i need to return the view instead of waiting for AuditService call.

I am new to async and await in MVC 4.

Upvotes: 2

Views: 2134

Answers (3)

Kamyar
Kamyar

Reputation: 18797

I think using Task is a better approach here:

if(saveStatus){
    new Task(AuditService.Add("Employee {0} added successfully", e.Name)).Start();
}  

Update:
As Stephen pointed out in his answer, this may cause your in-progress work to be lost.

Upvotes: 2

RredCat
RredCat

Reputation: 5421

You do it wrong. You can't run async inside any action of a simple controller. Because your client's code runs when server's code is completed and it isn't have the sense.

Depend on your target, you can do next:

Upvotes: 0

Stephen Cleary
Stephen Cleary

Reputation: 456322

As I describe on my blog, async does not change the HTTP protocol. What you're asking for is how to return early from an HTTP request; this doesn't have anything to do with async/await.

Regarding returning early from HTTP requests: You almost never want to do this.

If your "audit" service is actually a log - and you are perfectly fine with the occasional log message not being logged - then (and only then) you can use an approach like I describe on my blog.

Otherwise, you shouldn't return early. I.e., if your "audit" service is actually used for auditing, or if you expect your log to be accurate. In this case, you cannot return early.

Upvotes: 3

Related Questions