What is difference between Task.Factory.StartNew and new Thread().Start()? [duplicate]

試著忘記壹切 提交于 2019-12-11 11:02:59

问题


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.


回答1:


  • 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.



来源:https://stackoverflow.com/questions/23216417/what-is-difference-between-task-factory-startnew-and-new-thread-start

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!