What is difference between Task.Factory.StartNew a

2019-08-04 11:39发布

This question already has an answer here:

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条回答
爷、活的狠高调
2楼-- · 2019-08-04 11:57
  • 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.

查看更多
登录 后发表回答