Task.Factory.StartNew和新的Thread()之间有什么区别?Start()? [英] What is difference between Task.Factory.StartNew and new Thread().Start()?

查看:1600
本文介绍了Task.Factory.StartNew和新的Thread()之间有什么区别?Start()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DbContext(实体框架6.0)和1,000个对象。



对于每个对象,我开始将其保存到数据库或使用单独的线程更新其数据/任务使用相同的DbContext。



这是我得到的:




  • 对于线程:EntityCommandExecutionException - 已经有一个打开的DataReader与此命令关联,必须首先关闭。这个异常发生在第二个启动之后。

  • 对于任务:一切都很好。所有对象都被添加/更新。



我明白,由于使用相同的DbContext对象和多次调用,所以我得到线程异常但是我不确定。



问题:为什么我得到的差异以及线程异常?



我不太了解任务和TPL库。我已经使用了几个小规模项目的线程。

解决方案


  • 任务.Factory.StartNew :启动一个新的任务,它将在线程池线程中运行,或者可以在同一个线程中运行。如果它在一个线程池线程中运行,则线程在完成后返回到池中。线程创建/销毁是一个昂贵的过程。


  • 新的Thread()。Start():将始终运行在一个新的线程中,因此更昂贵。 / p>




异常表示正在从其他地方读取正在进行的数据集,您正在尝试打开另一个数据读者在同一时间。当使用任务时,也许你正在执行一个任务,这就是为什么你没有得到例外。



异常不是线程相关的。您可以通过打开数据读取器获得相同的异常,并尝试打开一个新的,但不关闭第一个。



我建议您考虑您的代码,并确保在使用之前需要使用线程。多线程过度使用会导致性能问题和难以置信的丑陋错误。


I have one DbContext (Entity Framework 6.0) and 1,000 objects.

For each object, I start to save its into database or update its data with a separate thread/task using the same DbContext.

This is what I got:

  • For thread: EntityCommandExecutionException - There is already an open DataReader associated with this Command which must be closed first. This exception occurred right after the second thead is started.
  • For task: everything is fine. All object is added/updated.

I understand that because of using the same DbContext object and multiple calls to it, so I got the exception with thread. But I'm not sure.

Question: Why do I get the differences as well as exception with thread here?

I don't understand much about the task and TPL library. I have used Thread for several small scale projects before.

解决方案

  • Task.Factory.StartNew : Starts a new task that will run in a thread pool thread or may run in the same thread. If it is ran in a thread pool thread, the thread is returned to the pool when done. Thread creation/destruction is an expensive process.

  • new Thread().Start() : Will always run in a new thread, therefore, it is more expensive.

The exception means that there is an ongoing data set being readed from somewhere else, and you are trying to open another data reader at the same time. When using tasks, maybe you are executing one task after the other, and that is why you don't get the exception.

The exception is not threading related. You can get the same exception by opening a data reader, and try to open a new one without closing the first.

I would suggest to review your code considering that, and ensure you need threading before use it. Multithreading overuse creates performance problems and incredibly ugly bugs.

这篇关于Task.Factory.StartNew和新的Thread()之间有什么区别?Start()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆