26

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.

  • 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. – Robert Harvey Aug 30 '13 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! – user2675751 Aug 30 '13 at 5:45
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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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