27

I have a controller in my mvc4 web application in which there is an action that needs to call another function. What happens in that function i.e. the return value is not important for my action. How i can call that function and never wait for it to be executed?

I think it can be done by async but my point is not to use resources, just call the function and never wait for it what ever happens.

Please give me some advise.

3
  • The only way you can do that is by passing it to another thread. There's no such thing as calling a function without resources, unless you just want it to be a no-op. Aug 30, 2013 at 5:34
  • thanks, i meant what is the best and optimized way, i think the best way is Task.Run and using WebApi in MVC, based on the link @user814064 mentioned, maybe i can just use a javascript solution, but i think that is not professional! Aug 30, 2013 at 5:45

1 Answer 1

40
private void Demo()
{
    // Do something, given that the result doesn't matter.
}

public void Do()
{
    Task.Factory.StartNew(this.Demo);

    // The following line will be executed without waiting for the result.
    DoSomethingElse();
}

Note that starting a method without caring about the result or about exceptions it can throw is risky.

If an exception is thrown in a Task, it will be hidden until you:

  1. Observe the Result,
  2. Wait() for the task, or:
  3. The GC calls the finalizer on the Task.

You can handle yourself 1. and 2. shortly after you call the method, or you can attach a continuation with myTask.OnComplete(myErrorHandler, TaskContinuationOptions.OnlyOnFaulted) to be run when the original task throws an exception. 3. will crash your process; don't do that.

1
  • 4
    Could you expand on "3. will crash your process; don't do that". Isn't this done automatically?
    – rdans
    Nov 5, 2014 at 19:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.