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

标签 c# multithreading taskfactory

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

当我调用这一行时:

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

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

但是,如果我添加一个等待,那么该方法就会被调用。

我使用 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 返回一个 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.

简单来说,等待是一个阻塞操作。

请看一下here了解更多相关信息。

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

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

关于c# - Task.Factory.StartNew 中的方法(操作)调用未立即调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33024398/

相关文章:

c# - StartCopyFromBlob 不适用于 Azure

c# - 声明枚举时,是否应将少于 256 个实体的类型强制为字节?

c++ - 对 std::lock 的调用是否可以传递已被调用线程锁定的资源?

JavaFX:控制台登录 TextArea + 多线程和任务

C# 如何使用主键在数据库中插入多行

c# - 如何强制 File.Move/File.Copy 使用特定的网络接口(interface)卡 (NIC) C#?

java - 服务器中的循环读取所有客户端套接字

c# - TaskFactory 内部任务永远不会被执行并且始终处于 WaitingForActivation 状态

c# - System.Threading.ThreadAbortException 在新线程中引发

.net - 多线程进程中的 parallel.for 或 task.startnew