Task.Factory.StartNew 中的方法(操作)调用未立即调用

Method (Action) call in Task.Factory.StartNew not being invoked immediately

我的印象是我可以调用这个线程,我的方法 "DoSomething" 中的任何内容都会开始发生,但显然不会。

当我调用这一行时:

Task.Factory.StartNew(() => 
ControllerClass.DoSomething("data"), 
CancellationToken.None, 
TaskCreationOptions.LongRunning, TaskScheduler.Default);

ControllerClass.DoSomething("data") 未执行。

但是,如果我添加 Wait,则会调用该方法。

我使用 LongRunning 选项的原因是该方法可以是 LongRunning,因为某些事情在它开始执行时还没有到位。是的,方法本身在调用内联时有效。只是它需要在一个线程中,这样主程序才能在这个线程做它的事情的同时继续。

顺便说一句,我也试过用这种方式调用它,结果相同:

 Task.Factory.StartNew(() =>
 ControllerClass.DoSomething("data")).ContinueWith
        (t =>
        {
            SendErrorEmail(t.Exception);
        }, TaskContinuationOptions.OnlyOnFaulted
        );

我是否遗漏了一些选项来告诉它立即开始执行方法调用?

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.

不,这不会发生。实际上,当你这样写的时候:

Task.Factory.StartNew(() => 
    ControllerClass.DoSomething("data"), 
    CancellationToken.None, 
    TaskCreationOptions.LongRunning, TaskScheduler.Default);

在掩护下,您的任务是进入队列,迟早会 运行 在 ThreadPool 的线程上。

根据MSDN

Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

对你的其他陈述:

However, if I add a Wait, then the method gets called.

这是真的,因为 TaskFactory.StartNew returns 一个 Task 对象。当我们调用任务的 Wait 方法时

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.

简而言之Wait是一个拦截动作

请查看 here 了解更多信息。

Am I missing some option to tell it to start executing the method call right away?

没有。据我所知,除非调用 wait,否则别无选择。