SqlBulkCopy.WriteToServer() keep getting “connection is closed”

前端 未结 3 1490
野性不改
野性不改 2021-01-22 07:44

This makes no sense to me but maybe someone with keener eyes can spot the problem.

I have a Windows service that uses FileSystemWatcher. It processes some files and upl

相关标签:
3条回答
  • 2021-01-22 07:52

    This looks to me to be a bug in the SqlBulkCopy implementation. If you run a (large) number of bulk copies in parallel in separate tasks concurrently, disable your network connection and then trigger a full garbage collection, you will reliably get this exception thrown on the GC's finalizer thread. It is completely unavoidable.

    That shouldn't happen because you are continuing the WriteToServerAsync task and handling the fault. But in the implementation, on error they start a new task that they don't continue or await.

    This still seems to be a bug in .NET 4.6.2.

    The only fix I can see is to subscribe to TaskScheduler.UnobservedTaskException and look for something in the stacktrace that identifies the issue. That isn't a fix by the way, it is a hack.

    0 讨论(0)
  • 2021-01-22 07:52

    Way late to throw this one on here but I was having what I thought was the same issue with SqlBulkCopy. Tried some of the steps in the other answers but with no luck. Turns out in my case that the actual error was caused by a string in the data going above the max length on one of the varchar columns, but for some reason the only error I was getting was the one about the closed connection.

    Strangely, my coworker tried the same thing, and got an actual error message about the varchar being out of bounds. So we fixed the data and everything worked, but if you're here because of this error and nothing else works, you might want to start looking for different issues in your data.

    0 讨论(0)
  • 2021-01-22 08:12

    Looks like an issue with it being Async.

    Please let me know if I wrong, but what I noticed is you have your SqlBulkCopy and ObjectReader in a using statement which is great, however, you are doing all the processing asynchronously. Once, you call it and it starts doing work, your using statements are disposing of your objects which will also kill your connection.

    The odd thing is that it sounds like it works sometimes, but perhaps it just becomes a race condition at that point.

    0 讨论(0)
提交回复
热议问题