I was under the impression that I could just make this thread call and whatever was in my method "DoSomething" would just start happening, but apparently not.
When I invoke this line:
Task.Factory.StartNew(() =>
ControllerClass.DoSomething("data"),
CancellationToken.None,
TaskCreationOptions.LongRunning, TaskScheduler.Default);
ControllerClass.DoSomething("data") is not executed.
However, if I add a Wait, then the method gets called.
The reason I'm using the LongRunning option is that the method can be LongRunning in certain things aren't in place when it start executing. And yes, the the method itself works when called inline. It is just that it needs to be in a thread so that the main program can continue while this thread does its thing.
By the way, I have also tried this way to call it and same results:
Task.Factory.StartNew(() =>
ControllerClass.DoSomething("data")).ContinueWith
(t =>
{
SendErrorEmail(t.Exception);
}, TaskContinuationOptions.OnlyOnFaulted
);
Am I missing some option to tell it to start executing the method call right away?
I was under the impression that I could just make this thread call and whatever was in my method "DoSomething" would just start happening, but apparently not.
No, this is not happening. Actually, when you write this:
Task.Factory.StartNew(() =>
ControllerClass.DoSomething("data"),
CancellationToken.None,
TaskCreationOptions.LongRunning, TaskScheduler.Default);
under the cover your task is get into a queue and sooner or later will be run on a thread of the ThreadPool
.
According to MSDN:
Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.
Ragarding you other statement:
However, if I add a Wait, then the method gets called.
This is true, because the TaskFactory.StartNew
returns a Task
object. when we call the Wait
method of a task
If the current task has not started execution, the Wait method attempts to remove the task from the scheduler and execute it inline on the current thread. If it is unable to do that, or if the current task has already started execution, it blocks the calling thread until the task completes.
In a few words Wait
is a blocking action.
Please have a look here for more information on this.
Am I missing some option to tell it to start executing the method call right away?
No. Unless calling wait there isn't any alternative, as far as I am aware of.