Removing Connections
The connection pooler removes a connection from the pool after it has
been idle for a long time, or if the pooler detects that the
connection with the server has been severed.
Note that a severed connection can be detected only after attempting
to communicate with the server. If a connection is found that is no
longer connected to the server, it is marked as invalid.
Invalid connections are removed from the connection pool only when
they are closed or reclaimed.
If a connection exists to a server that has disappeared, this
connection can be drawn from the pool even if the connection pooler
has not detected the severed connection and marked it as invalid.
This is the case because the overhead of checking that the connection
is still valid would eliminate the benefits of having a pooler by
causing another round trip to the server to occur.
When this occurs, the first attempt to use the connection will detect
that the connection has been severed, and an exception is thrown.
Basically what you are seeing is that exception in the last sentence.
A connection is taken from the connection pool, the application does
not know that the physical connection is gone, an attempt to use it is
done under the assumption that the physical connection is still there.
And you get your exception.
There are a few common reasons for this.
- The server has been restarted, this will close the existing connections.
In this case, have a look at the SQL Server log, usually found at:
C:Program FilesMicrosoft SQL Server\MSSQLLOG
If the timestamp for startup is very recent, then we can suspect that
this is what caused the error. Try to correlate this timestamp with
the time of exception.
2009-04-16 11:32:15.62 Server Logging SQL Server messages in file
‘C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLLOGERRORLOG’.
- Someone or something has killed the SPID that is being used.
Again, take a look in the SQL Server log. If you find a kill, try to
correlate this timestamp with the time of exception.
2009-04-16 11:34:09.57 spidXX Process ID XX was killed by
hostname xxxxx, host process ID XXXX.
- There is a failover (in a mirror setup for example) again, take a look in the SQL Server log.
If there is a failover, try to correlate this timestamp with the time
of exception.
2009-04-16 11:35:12.93 spidXX The mirrored database “” is changing roles from “PRINCIPAL” to “MIRROR” due to
Failover.
- Remove From My Forums
A transport-level error has occurred when receiving results from the server (provider: TCP Provider, error: 0 — The specified network name is no longer available.)
-
Question
-
I’ve a simple SSIS Package to transfer data between two servers, let’s say from SERVER01 (source) to SERVER02 (destination). When I test my SSIS package localy everything works great. When I deploy it on the SERVER02 it fails with an error:
A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 — The specified network name is no longer available.)
So I tested my «select query» directly in SSMS: Execute on my laptop — ok. Execute in SSMS on SERVER02 — fails with same error message. Execute on other servers — ok.
So it means it’s related to the SERVER02. It’s virtual machine running Windows 2012 and SQL Server 2012. I can ping the SERVER01 without any problems. The data is about 170.000 rows and 20 columns.
The query breaks after some time, and it’s random. Sometimes I get 10.000 records before it breaks, sometimes 80.000.
We’ve 4GB free RAM (from 16GB). When I run the query memory usage doesn’t change (70%) .
Other smaller queries run without any problems.
Can someone point me how to solve this issue?
Answers
-
Hi toLL_net,
This may be a network TCP timeout issue. You may find another error message “A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 — The semaphore timeout period has expired.)” around. The issue can
be caused by various factors. Here are some suggestions for your reference:- SQL Server priority boost issue. Raising the priority too high may drain resources from essential operating system and network functions and the priority boost feature will be removed in a future version of SQL Server. To disable the priority boost of SQL
Server 2012, please see
Configure the priority boost Server Configuration Option. - Network Interface Card (NIC) driver issue. Please update the NIC driver on SERVER02 to the latest version.
- Network packet size of the SQL Server issue. The default value of the network packet size is 4096 bytes. For most applications, the default packet size is best. To configure the network packet size, please see
Configure the network packet size Server Configuration Option.
Hope this helps.
Regards,
Mike Yin
TechNet Community Support-
Marked as answer by
Sunday, December 22, 2013 1:16 PM
- SQL Server priority boost issue. Raising the priority too high may drain resources from essential operating system and network functions and the priority boost feature will be removed in a future version of SQL Server. To disable the priority boost of SQL
- Remove From My Forums
-
Question
-
I have asked similar question on IIS and SQL Server Forums, but I am yet to get a solution. I have realized this is highly related to Entity Framework. Let me explain.
The following code generates the error about once every two days:
using (Models.FooEntities context = new Models.FooEntities()) { context.CommandTimeout = 300; Models.tblFoo foo = new Models.tblFoo(); foo.DateTime = DateTime.Now; ... try { context.SaveChanges(); } catch (EntityDataSourceValidationException edsve) { ... } catch (Exception ex) { //"A transport-level error has occurred when receiving results from the server" is caught here } }
Once this happens, the only way to remedy it is rebooting the hosting machine — a Windows 7 box. None of the following would help:
- Recycling app pools.
- Restarting the web application.
- Restarting IIS.
- Restarting SQL server.
Here may be the most important fact: only web applications using Entity Framework generate this error.
When it happens, other applications that do not use Entity Framework work fine with the same SQL database.Is there a way to reset Entity Framework without rebooting the machine?
Hong
Answers
-
Hi Fred, it has been working fine since I added the following to the connection string 2 days ago:
Connection Lifetime=3;Max Pool Size=3
I think I will be able to declare this is a remedy for the problem by the end of tomorrow if the problem will not occur. I will report back.
Hong
-
Marked as answer by
Thursday, October 31, 2013 9:38 AM
-
Marked as answer by
In our Vb.net application(userd within a local network connection inside a office), which is used from long time now some of the users get the errors only sometimes a day
A transport-level error has occurred when sending the request to the server. (provider: TCP Provider, error: 0 — An existing connection was forcibly closed by the remote host.
I have already checked following
-
All databases are set to autoclose OFF
-
Didn’t find much network problems and network speed is good.
-
When I checked in SSMS the under server properties remote query time-out set to 600 seconds
-
I checked sql server log and no errors found relating to it or same error message
So what may be the reason for this error? And how to troubleshoot it?
asked May 3, 2014 at 7:00
IT researcherIT researcher
3,11515 gold badges54 silver badges78 bronze badges
0
If an application opens a connection (successfully) to SQL Server, and leaves it open in anticipation of sending a (or possible ‘another’) query, and in the meantime, SQL kills that connection for some reason (eg, service restarts, or a kill command is sent), then when the connection (which thinks it’s open) tries to send a command, you’ll get this error.
So catch the error in your application, and reconnect. Then try the command again.
answered May 3, 2014 at 7:06
I mostly see this error if for some reason the network connectivity was lost, even for a few seconds. That could be someone disconnecting a cable, an unstable wifi connection, a bad network switch, computer that goes to sleep (it’s on by default on Win7 and up), Windows update updating a network driver, etc.
answered May 5, 2014 at 0:58
ManuH68ManuH68
2061 silver badge3 bronze badges
1
I ran across the same error a while back and meant to post my answer, but I couldn’t log in and simply forgot. I happened upon this question again and will give my answer as best as I can remember as it’s quite obscure and I could find no mention of it anywhere else.
This error is returned from MS-SQL databases when passing some form of invalid date to an SP from .NET (and potentially other sources). IIRC, I was passing in a .NET MinDate (ie. default value). Basically, just check your date parameters and make sure they are sensible!
answered Jun 4, 2015 at 11:27
I got exactly the same error in my application. It updates many records in single transaction. I fixed this by increasing SqlCommand.CommandTimeout parameter.
answered Mar 27, 2018 at 12:12
In my case someone started a wireless printer with a fixed IP on the network, causing an IP conflict. After killing the printer all working fine.
answered Dec 9, 2020 at 19:57
In my case it was caused by vpn (kerio) and I was able to easily bypass that using ssh tunneling (ssh -R) the database port to 127.0.0.1:[someportnumber] and connecting the app the it
answered Aug 25, 2022 at 15:07
HamedHHamedH
1012 bronze badges
I got this error due to SQL Server not liking one of my commented out lines of SQL.
My advice is to start with the simplest code to validate that it is not a connection issue and then work up from there.
The commented out line was —EXEC master..xp_cmdshell ‘bcp … for which the remote computer did not have permission to run.
There is an almost identical line later on in the code that was accepted, so I think this is some vague security patch error.
You would think a commented out line would have no affect on connectivity issues, but here we are.
answered Sep 26, 2022 at 16:13
in my case this error getting if your C drive space low,and every second generate new logs files.
So resolution is all logs delete in c drive then working fine again.
answered Aug 16, 2016 at 4:51
Hi All,
In our production environment we see sporadic exceptions stating A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)
.
At the moment we’re using a pretty simple connection string:
Server=172.24.32.7;Database=GetYourPet_1_1_0;User Id=***;Password=***;MultipleActiveResultSets=true
The database server is a separate machine from the web server, so there is networking involved. So I’m not sure why the connections go down in the first place, but then I’m wondering if there’s a way to catch this exception more generically and retry? And / or should we have more specific settings in the connection string about the size of the connection pool?
Sort of desperate here… any help would be great.
If you are seeing an exception, include the full exceptions details (message and stack trace).
Exception message: A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)
Stack trace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) ~
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) ~
at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error) ~
at System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync() ~
at System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket() ~
at System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer() ~
at System.Data.SqlClient.TdsParserStateObject.TryReadByte(Byte& value) ~
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) ~
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() ~
at System.Data.SqlClient.SqlDataReader.get_MetaData() ~
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) ~
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest) ~
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) ~
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) ~
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) ~
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, String executeMethod, IReadOnlyDictionary`2 parameterValues, Boolean closeConnection) ~
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues) ~
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable.Enumerator.BufferlessMoveNext(Boolean buffer) ~
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](Func`2 operation, Func`2 verifySucceeded, TState state) ~
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.<_ShapedQuery>d__3`1.MoveNext() ~
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source) ~
at lambda_method(Closure , QueryContext ) ~
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass20_0`1.<CompileQueryCore>b__0(QueryContext qc) ~
at GetYourPet.Services.MeetUpService.Get(String adopterUserId, Int32 petId, ApplicationUserRole applicationUserRole) in D:a1sGetYourPetsrcGetYourPetServicesMeetUpService.cs:line 45 ~
at GetYourPet.Controllers.MeetUpsController.Get(String adopterUserId, Int32 petId) in D:a1sGetYourPetsrcGetYourPetControllersMeetUpsController.cs:line 63
Steps to reproduce
There are no deterministic steps to reproduce
line 45 from MeetUpService.cs: MeetUp meetUp = _applicationDbContext.MeetUps.Where(mu => mu.AdopterUserId == adopterUserId && mu.PetId == petId).FirstOrDefault();
Further technical details
EF Core version: 1.1.0
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows Server 2012 R2
IDE: Visual Studio 2015 w/ Update 3 (but that’s just what we develop with… the issue is occurring in our production environment)
Я получаю ошибку SQL Server:
Произошла ошибка транспортного уровня при получении результатов сервер. (поставщик: общая память Провайдер, ошибка: 0 — Ручка недействительным.)
Я запускаю Sql Server 2008 SP1, Windows 2008 Standard 64 бит.
Это веб-приложение .NET 4.0. Это происходит, когда запрос поступает на сервер. Это прерывисто. Любая идея, как я могу ее решить?
Ответ 1
Соединение с базой данных закрывается сервером базы данных. Соединение остается действительным в пуле подключений вашего приложения; в результате, когда вы берете общую строку соединения и пытаетесь выполнить ее, вы не сможете добраться до базы данных. Если вы разрабатываете Visual Studio, просто закройте временный веб-сервер на панели задач.
Если это происходит в процессе производства, сброс пула приложений для вашего веб-сайта должен переработать пул соединений.
Ответ 2
Попробуйте выполнить следующую команду в командной строке:
netsh interface tcp set global autotuning=disabled
Это отключает возможности автоматического масштабирования сетевого стека
Ответ 3
Для тех, кто не использует IIS, у меня была эта проблема при отладке с Visual Studio 2010. Я закончил все процессы отладчика: WebDev.WebServer40.EXE, который решил проблему.
Ответ 4
У меня была та же проблема. Я перезапустил Visual Studio и исправил проблему
Ответ 5
Все, что вам нужно, это остановить сервер разработки ASP.NET и снова запустить проект
Ответ 6
Получил это, всегда после приблизительно 5 минут работы. Расследовали и обнаружили, что предупреждение от e1iexpress всегда происходило до сбоя. По-видимому, это ошибка, связанная с некоторыми адаптерами TCP/IP. Но переход от WiFi к проводному не повлиял на него.
Итак, попробовал Plan B и перезапустил Visual Studio. Затем он работал нормально.
В ближайшем исследовании я заметил, что при правильной работе сообщение The Thread '<No Name>' has exited with code 0
произошло почти точно в момент, когда в предыдущих попытках произошел сбой. Некоторые из Google Google показывают, что это сообщение появляется, когда (среди прочего) сервер обрезает пул потоков.
Предположительно, в пуле потоков был фиктивный поток, и каждый раз, когда сервер пытался «обрезать» его, приложение заняло.
Ответ 7
Если вы подключены к базе данных через Microsoft SQL Server Management, закройте все свои подключения и повторите попытку.
Если бы эта ошибка возникла при подключении к другой базе данных Azure и работала для меня, когда она была закрыта.
Все еще не знаю, почему..
Ответ 8
Вы получите это сообщение, когда ваш script заставляет SQL-службу останавливаться по некоторым причинам. поэтому, если вы снова запустите службу SQL, возможно, ваша проблема будет решена.
Ответ 9
Ошибки уровня транспорта часто связаны с подключением к серверу sql, который прерывается… обычно в сети.
Время ожидания истекает, как правило, вызывается, когда SQL-запрос занимает слишком много времени.
Так мало вариантов:
- Проверить подключение в VPN (если используется) или любой другой инструмент
- Перезапустить IIS
- Перезапустить машину
- Оптимизация запросов sql.
Ответ 10
Я знаю, что это может не помочь всем (кто знает, может быть, да), но у меня была такая же проблема, и через какое-то время мы поняли, что причиной является что-то из самого кода.
Компьютер, пытающийся связаться с сервером, находился в другой сети, соединение можно было установить, но затем удалить.
Как мы это исправили, было добавление статического маршрута к компьютеру, что обеспечило прямой доступ к серверу без прохождения через брандмауэр.
route add –p YourServerNetwork mask NetworkMask Router
Пример:
route add –p 172.16.12.0 mask 255.255.255.0 192.168.11.2
Я надеюсь, что это поможет кому-то, лучше иметь это, по крайней мере, как подсказку, поэтому, если вы сталкиваетесь с этим, вы знаете, как его решить.
Ответ 11
Я получил ту же ошибку в среде разработки Visual Studion 2012, остановил IIS Express и перезапустил приложение, он начал работать.
Ответ 12
Посмотрите на блог MSDN, в котором описывается эта ошибка:
Удаление соединений
Пул соединений удаляет соединение из пула после того, как он долгое время простаивали, или если пул обнаруживает, что соединение с сервером было отключено.
Обратите внимание, что отключенное соединение может быть обнаружено только после попытки для связи с сервером. Если обнаружено соединение, которое не является более длинный подключенный к серверу, он помечен как недопустимый.
Недействительные подключения удаляются из пула соединений только тогда, когда они закрыты или возвращены.
Если соединение существует на сервере, который исчез, это соединение может быть выведено из пула, даже если пул соединений не обнаружил отключенное соединение и отметил его как недействительный.
Это так, потому что накладные расходы на проверку того, что соединение остается в силе, исключит преимущества наличия пула в результате чего произойдет еще одна поездка на сервер.
Когда это произойдет, первая попытка использовать соединение обнаружит что соединение было отключено, и выбрано исключение.
В основном то, что вы видите, это исключение в последнем предложении.
Соединение берется из пула соединений, приложение не знаю, что физическое соединение ушло, попытка его использования сделано в предположении, что физическое соединение все еще существует.
И вы получите свое исключение.
Есть несколько общих причин для этого.
- Сервер был перезапущен, это приведет к закрытию существующих подключений.
В этом случае просмотрите журнал SQL Server, который обычно находится по адресу: C:Program FilesMicrosoft SQL Server\MSSQLLOG
Если отметка времени для запуска очень недавно, мы можем подозревать, что это и послужило причиной ошибки. Постарайтесь сопоставить эту метку времени с время исключения.
2009-04-16 11: 32: 15.62 Server Logging Сообщения SQL Server в файле ‘C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLLOGERRORLOG.
- Кто-то или что-то убил используемый SPID.
Снова загляните в журнал SQL Server. Если вы найдете убийство, попробуйте сопоставить эту метку времени со временем исключения.
2009-04-16 11: 34: 09.57 идентификатор процесса spidXX XX был убит имя хоста xxxxx, идентификатор хост-процесса XXXX.
- Повторите попытку (например, в зеркальной настройке), загляните в журнал SQL Server.
Если происходит переход на другой ресурс, попробуйте сопоставить эту метку времени с временем исключения.
2009-04-16 11: 35: 12.93 spidXX Зеркальная база данных «меняет роли от» PRINCIPAL «до» MIRROR» из-за Failover.
Ответ 13
У меня была такая же проблема. Я решил это, обрезая SQL Server LOG.
Проверьте это, а затем сообщите нам, если это решение вам помогло.
Ответ 14
Для меня ответ заключается в том, чтобы обновить ОС с 2008 года2 до 2012 года2, решение iisreset или перезапустить приложение не сработало для меня.
Я также попытался включить параметр TCP Chimney Offload, но я не перезапустил сервер, потому что это производственный сервер, который тоже не работает.
Ответ 15
Для меня решение было совершенно другим.
В моем случае у меня был объект objectsource, который требовал параметр datetimestamp. Несмотря на то, что этот параметр ODS ConvertEmptyStringToNull был истинным, 1/1/0001 передается SelectMethod. Это, в свою очередь, вызвало исключение переполнения sql datetime, когда это datetime было передано серверу sql.
Добавлена дополнительная проверка для datetime.year!= 0001, и это решило для меня.
Странно, что это вызовет ошибку транспортного уровня, а не ошибку переполнения datetime.
В любом случае..
Ответ 16
Мы столкнулись с этой ошибкой недавно между нашим бизнес-сервером и нашим сервером базы данных.
Решение для нас состояло в том, чтобы отключить «Разделение IP-адресов» на сетевых интерфейсах.
Затем ошибка исчезла.
Ответ 17
Одна из причин, по которой я нашел эту ошибку, — « Packet Size = xxxxx» в строке подключения. если значение xxxx слишком велико, мы увидим эту ошибку. Удалите это значение и позвольте серверу SQL обрабатывать его или поддерживать его на низком уровне, в зависимости от сетевых возможностей.
Ответ 18
Это случилось со мной, когда я пытался восстановить базу данных SQL и проверил следующий флажок в закладке Options
,
Поскольку это отдельный сервер базы данных, просто закрывающий SSMS и возобновляющий его, решил проблему для меня.
Ответ 19
В моем случае служба сервера SQL Server остановлена. Когда я перезапустил службу, которая позволила мне запустить запрос и устранить ошибку.
Также неплохо изучить ваш запрос, чтобы узнать, почему запрос остановил эту службу
Ответ 20
Это происходит, когда база данных удаляется и воссоздается, некоторые общие ресурсы по-прежнему считают, что база данных по-прежнему существует, поэтому, когда вы повторно запускаете запрос выполнения для создания таблиц в базе данных после его восстановления, ошибка не будет отображаться и сообщение Command(s) completed successfully.
будет отображаться вместо сообщения об ошибке Msg 233, Level 20, State 0, Line 0 A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)
.
Просто игнорируйте эту ошибку, когда вы бросаете и воссоздаете базы данных и повторно выполняете свои DDL-запросы без каких-либо проблем.
Ответ 21
Недавно я столкнулся с той же проблемой, но я не смог получить ответ в google.
Поэтому подумал о том, чтобы поделиться им здесь, чтобы он мог помочь кому-то в будущем.
Ошибка:
Во время выполнения запроса запрос будет содержать несколько выходных данных, тогда он будет вызывать ошибку ниже.
«Ошибка транспортного уровня произошла при получении вывода из server (TCP: поставщик, ошибка: 0 — указанное сетевое имя больше не доступны»
Решение:
- Проверить поставщика связанного сервера
- В свойствах этого поставщика включите опцию «Разрешить inprocess» для этого конкретного поставщика, чтобы устранить проблему.
I’m trying to connect to an Azure SQL database and everything is working fine except on one table. When I try to select that table and edit the query, it stalls for a while and then eventually gives me the following error:
DataSource.Error: Microsoft SQL: A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The specified network name is no longer available.) Details: DataSourceKind=SQL DataSourcePath=thisisafakeurl.database.windows.net;NameOfDatabaseGoesHere Message=A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The specified network name is no longer available.) Number=64 Class=20
It only happens on this one table. Everything else is just fine. It happens to be the largest table in the database, both in terms of rows and columns.
I have seen a suggestion that disabling «Enable parallel loading of tables» in the Data Load Options panel would fix this problem. Initially it did, and disabling that does allow other queries on this table that I’ve already written to refresh (queries that restrict the number of rows and columns). However as of this morning the error is back whenever I try to load a fresh preview to begin a new query. I know two or three more columns were added to the table yesterday.
So is there some timeout setting or something that can be changed on Azure to solve this? I think I’ve run out of Power BI settings to turn off.
Did I answer your question? Mark my post as a solution!
Proud to be a Super User!
We have a program written in C# using Visual Studio 2012 and .NET 4.0 / .NET 4.5. It rapidly executes many queries in Microsoft SQL Server 2008 R2 and then exits. Executed query count varies from several hundred to many thousand.
Today, when executed particular task with very many queries, I noticed an error in the log file:
A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
at System.Data.SqlClient.TdsParserStateObject.ReadSni(DbAsyncResult asyncResult, TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParserStateObject.ReadNetworkPacket()
at System.Data.SqlClient.TdsParserStateObject.ReadBuffer()
at System.Data.SqlClient.TdsParserStateObject.ReadByte()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader()
at MyTestApp.Program.QueryOneLineOneValue(String cmdText)
at MyTestApp.Program.Worker(String[] args)
at MyTestApp.Program.Main(String[] args)
At first, the error message lead me to think that something is wrong with the network. “Physical connection is not usable”… anyway it didn’t say anything useful… and SQL Server log file didn’t have anything useful either.
A quick Google search revealed that many people have the same problem:
- Minimizing Connection Pool errors in SQL Azure — it has code example with an serious bug, and it leads to Reliability Update 1 for the .NET Framework 4 which may help judging from the description – “Issue 14 – A transport-level error has occurred when sending the request to the server.” I didn’t tried it, mostly because it talks about Azure services.
- Discussion in the Microsoft SQL Server Database Engine forum which leads to MSDN article about SQL Server Connection Pooling which again does not help much, because I have only one connection in my application.
- And a couple not very useful pages from the Stack Overflow: One suggests to call ClearAllPools and another one is about Azure again.
Again, I had to find solution by myself. I looked at the code and didn’t see anything unusual. I did another run under the VS debugger, and after a while the same exception was thrown. Looking under debug log file, I noticed that program stopped in the same place that in the production server. And by the same place I mean, the same amount of SQL commands were executed.
I quickly put a counter on right before SQL command execution and found that .NET throws exception always on 32767 command. 32767 is very familiar constant for programmers, and it is obvious that some resource leakage is happening. A quick glance at the code again revealed that a call to Close or Using statement is missing.
SqlConnection conn;
private static void QueryOneLineOneValue(String cmdText)
{
string q = "SELECT ... FROM cmdText...";
SqlCommand command =
new SqlCommand(q, conn);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//do something with the data...
}
reader.Close(); //this line was missing
}
Я перепробовал все другие сообщения об ужасной «ошибке 19» и обнаружил, что те немногие, у которых есть ответы, не подходят или не помогают, отсюда и этот новый пост. Это очень серьезная потенциальная проблема для всех пользователей Azure + EF.
Первое появление:
Я использую последнюю версию всего в проекте VS2013 EF6.1 Razor (пакеты перечислены в конце). База данных размещена в SQL Azure.
После запуска моего веб-приложения несколько раз (в среде разработки) я получаю следующую ошибку: A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)
Линия, на которой он умирает, всегда такая:
Я понимаю, что ошибка связана с пулом соединений (и исчерпанием соединений), но я нигде не могу обнаружить утечку.
Когда я получаю доступ к членству в OWIN и другим функциям базы данных в приложении, у меня есть DatabaseContoller
, от которого наследуются все остальные контроллеры. Это создает все соответствующие компоненты и избавляется от них.
DatabaseController.cs
[Authorize]
public class DatabaseController : Controller
{
#region properties
/// <summary>
/// User manager - attached to application DB context
/// </summary>
protected UserManager<ApplicationUser> UserManager { get; set; }
/// <summary>
/// Role manager - attached to application DB context
/// </summary>
protected RoleManager<IdentityRole> RoleManager { get; set; }
/// <summary>
/// Application DB context
/// </summary>
protected ApplicationDbContext ApplicationDbContext { get; set; }
/// <summary>
/// Database context used by most controllers
/// </summary>
protected ApplicationEntities Context { get; set; }
#endregion properties
#region Constructors
public DatabaseController()
{
this.Context = new ApplicationEntities ();
this.ApplicationDbContext = new ApplicationDbContext();
this.UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.ApplicationDbContext));
this.RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(this.ApplicationDbContext));
this.UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager) { AllowOnlyAlphanumericUserNames = false };
}
#endregion Constructors
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (UserManager != null)
{
this.UserManager.Dispose();
this.UserManager = null;
}
if (this.RoleManager != null)
{
this.RoleManager.Dispose();
this.RoleManager = null;
}
if (this.ApplicationDbContext != null)
{
this.ApplicationDbContext.Dispose();
this.ApplicationDbContext = null;
}
if (this.Context != null)
{
this.Context.Dispose();
this.Context = null;
}
}
base.Dispose(disposing);
}
}
Пакеты установлены
<package id="Antlr" version="3.5.0.2" targetFramework="net45" />
<package id="bootstrap" version="3.1.1" targetFramework="net45" />
<package id="EntityFramework" version="6.1.0" targetFramework="net45" />
<package id="jQuery" version="1.11.0" targetFramework="net45" />
<package id="jQuery.Validation" version="1.11.1" targetFramework="net45" />
<package id="json2" version="1.0.2" targetFramework="net45" />
<package id="Microsoft.AspNet.Identity.Core" version="2.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Identity.EntityFramework" version="2.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Identity.Owin" version="2.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Mvc" version="5.1.1" targetFramework="net45" />
<package id="Microsoft.AspNet.Razor" version="3.1.2" targetFramework="net45" />
<package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi" version="5.1.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.1.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.1.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.1.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebPages" version="3.1.2" targetFramework="net45" />
<package id="Microsoft.jQuery.Unobtrusive.Validation" version="3.1.2" targetFramework="net45" />
<package id="Microsoft.Owin" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Host.SystemWeb" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.Cookies" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.Facebook" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.Google" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.MicrosoftAccount" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.OAuth" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.Twitter" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" />
<package id="Modernizr" version="2.7.2" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.2" targetFramework="net45" />
<package id="Owin" version="1.0" targetFramework="net45" />
<package id="Owin.Security.Providers" version="1.3.1" targetFramework="net45" />
<package id="Respond" version="1.4.2" targetFramework="net45" />
<package id="WebGrease" version="1.6.0" targetFramework="net45" />
Предполагая, что это утечка соединения, как я могу отследить источник утечки?
Если вам нужна дополнительная информация, просто спросите.
Обновление: 22 мая 2014 г. Предлагается вторая награда
У меня все еще та же проблема, с некоторыми небольшими изменениями проекта, внесенными с момента последней публикации, поэтому я опубликую последние подробности ниже.
Я добавил Connection Lifetime=3;Max Pool Size=3;
в свои строки подключения на основе этот пост.
Обновление: 23 мая 2014 г. ошибка все еще возникает
На следующий день после отладки несколько десятков раз эта ошибка вернулась.
Обновление: 11 июня 2014 г.
После двух наград и бесчисленных расследований Google (на этот вопрос нет реального ответа), я должен предположить, что это недостаток Entity Framework 6, который я каким-то образом вызываю.
Дополнительная информация:
У меня была такая же ошибка в проекте WinForm, подключитесь к Azure. В этом случае я случайно не очищал список объектов после добавления каждых 20 новых элементов.
Каждый раз, когда код запускался, он добавлял еще 20 записей и обновлял поле DateModified
для всех из них. К тому времени, когда он достиг 1700 обновляемых записей, он внезапно выдал ужасную «ошибку 19 — Физическое соединение не используется». После этого мне нужно было перезапустить мой отладочный IIS, чтобы он вообще заработал.
Очевидно, что код подвергся огромному количеству обновлений, и, возможно, что-то в этом поможет кому-то придумать что-нибудь .
2 ответа
Лучший ответ
Ошибка 19 не является ошибкой связи! (или не просто ошибка связи)
Просто убедитесь, что в вашем запросе LINQ to SQL есть все необходимые вызовы .Include(x=>x.ForeignTable)
!
Обновлено в августе 2015 г. (возможное решение, по крайней мере для некоторых сценариев):
У нас только что был 100% повторный случай этой проблемы, который мы смогли решить с помощью тестирования методом проб и ошибок, так что это вполне может быть решением или, по крайней мере, дать подсказки о том, что искать.
Сценарий:
- Ошибка возникала только в сборках выпуска, работающих под IIS. Этого не происходило при отладке или в IIS Express.
- Мы также включили профилирование SQL, чтобы увидеть, когда и где на самом деле был поражен сервер.
- Рассматриваемый запрос извлекал совпадающие записи, а затем создавал модели представления в итерации результатов
foreach
(т. Е. Ленивая оценка). Модель представления зависела от значения в связанной таблице запрашиваемого объекта.
Тестирование:
Первая попытка : удалите все сложные фильтры по запросу.
- Результат: по-прежнему не удалось с ошибкой 19
Вторая попытка: добавьте ToList()
в запрос, чтобы заставить запрос выполняться до завершения немедленно.
- Результат: успешно !!! (очевидно, что здесь что-то происходит)
Третья попытка: удалите ToList()
и добавьте .Include(x=>x.ForeignTable)
в запрос, чтобы принудительно включить соответствующие данные.
- Результат: успех !
Моя новая теория:
Если вы случайно пропустите Include
сторонней таблицы, EF случайно не сможет получить связанные данные при ленивом вычислении. Это может привести к печально известной ошибке 19.
Поскольку в Identify Framework существуют отношения внешнего ключа, вы можете предположить, что также отсутствует .Include()
или эквивалент в запросе где-то в OWIN. Это может быть причиной случайной проблемы при использовании OWIN или других запросов.
Примечания:
- Ключевым моментом, который следует убрать, является то, что ошибка 19 не является ошибкой связи. Запросы попадают на SQL-сервер. На стороне клиента возникает проблема, связанная с невозможностью получить связанные данные.
Пауза для аплодисментов (мы очень рады, что это нашли)
Обновлено 28 августа 2015 г .:
Только что сегодня снова произошла ужасная ошибка 19, связанная с подключением к локальной базе данных SQL (обычно это была проблема с Azure для меня). Основываясь на результатах выше, я просто добавил оператор .Include(x=>x.ForeignTable)
там, где это необходимо, и проблема исчезла! Кажется, это проблема того, что EF не всегда может лениво загружать информацию о связанных таблицах.
8
Gone Coding
21 Сен 2015 в 10:27