Internal net framework data provider error 1

I'm developing a WinForm app with Visual Studio 2012 Ultimate edition with all service pack, C# and .NET Framework 4.5. I get this exception: Internal .Net Framework Data Provider error 1 With t...

I’m developing a WinForm app with Visual Studio 2012 Ultimate edition with all service pack, C# and .NET Framework 4.5.

I get this exception:

Internal .Net Framework Data Provider error 1

With this stack:

   en System.Data.ProviderBase.DbConnectionInternal.PrePush(Object expectedOwner)
   en System.Data.ProviderBase.DbConnectionPool.PutObject(DbConnectionInternal obj, Object owningObject)
   en System.Data.ProviderBase.DbConnectionInternal.CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory)
   en System.Data.SqlClient.SqlConnection.CloseInnerConnection()
   en System.Data.SqlClient.SqlConnection.Close()
   en AdoData.TRZIC.DisposeCurrentConnection() 
   en AdoData.TRZIC.Finalize() 

In the destructor:

~TRZIC()
{
    DisposeCurrentConnection();

    if (this.getCodeCmd != null)
        this.getCodeCmd.Dispose();
}

private void DisposeCurrentConnection()
{
    if (this.conn != null)
    {
        if (this.conn.State == ConnectionState.Open)
            this.conn.Close();

        this.conn.Dispose();
        this.conn = null;
    }
}

I get the exception in line this.conn.Close();.

And conn is private SqlConnection conn = null;

Do you know why?

Patrick Hofman's user avatar

asked Apr 9, 2014 at 12:36

VansFannel's user avatar

VansFannelVansFannel

44.5k106 gold badges353 silver badges610 bronze badges

1

I have found the solution here.

Basically it boils down to this:

Caution

Do not call Close or Dispose on a Connection, a DataReader, or any other managed object in the Finalize method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a Finalize method in your class definition. For more information, see Garbage Collection.

Patrick Hofman's user avatar

answered Apr 9, 2014 at 12:48

VansFannel's user avatar

VansFannelVansFannel

44.5k106 gold badges353 silver badges610 bronze badges

1

This is not answer but I strongly suggest you to dispose connections using using. Then you don’t need to concern about disposing objects.

using (SqlConnection connection = new SqlConnection(connectionString)) 
{    
    try    
    {
        connection.Open();
        SqlCommand command = new SqlCommand("......", connection);
        command.ExecuteNonQuery();    
    } 
    catch (Exception) 
    { 
        /*Handle error*/ 
    }
}

Patrick Hofman's user avatar

answered Apr 9, 2014 at 12:51

Reza's user avatar

  • Remove From My Forums
  • Question

  • I am getting «Internal .Net Framework Data Provider error 1» error while calling execute reader.

    Any body has idea what is the cause and fix?

Answers

  • Weird errors like this are often the result of multi-threading access to objects that are not threadsafe. Even if your code is not explicitly creating multiple threads, you have to be careful of situations where multiple threads may be used internally.

    I noticed that your call stack shows that the SqlDataReader.Close call is coming from your Finalize method (it’s directly coming from Dispose, but Dispose is being called by Finalize). It is not safe to call any managed objects in Finalize, because it is called non-deterministically by the garbage collector on a separate thread. The SqlDataReader.Close documentation explicitly calls this out:

    SqlDataReader.Close Method
    http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.close.aspx

    Caution 
    Do not call Close or Dispose on a Connection, a DataReader, or any other managed object in the Finalize method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a Finalize method in your class definition. For more information, see Garbage Collection.

    You should explicitly close the SqlDataReader when you are done using it, before finalization. If you do that and are still running into problems, post back again with a new error message and call stack (if they have changed).

    Thanks,
    Sarah

5

15 апреля 2009 года

hardcase

4.5K / / 09.08.2005

Вроде можно обойтись без контекстных синглтонов и, как следствие, без открытых статических методов/свойств

Но придется тогда передавать текущий контекст через аргументы всех методов — а это неудобно может быть. Статическое свойство удобнее, так как доступно отовсюду, и одновременно потоко-изолировано.

Просто, я так понял, что топикстартеру нужен был механизм, позволяющй получать объект соединения из немалого числа вложенных фунций, без передачи его через аргументы, плюс некий механизм безопасного управления этим ресурсом.

Код:

using (new ResouceContext()) {
… вызовы функций
    ResourceContext.Current.
… возвраты из них
…. и еще всякий код
}

[quote=Lei fang] Я правильно сделал эту штуку с контекстом?[/quote]
Фактическое соединение к БД лучше открывать в момент первого обращения к объекту соединения:

Код:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;

namespace ConsoleApplication1 {

    public sealed class ResourceContext : IDisposable {

        public ResourceContext(string connection_string) {
            this._previous_context = _current_context;
            // TODO: захват ресурсов…
            this._connection = new SqlConnection(connection_string);

            _current_context = this;
        }

        ~ResourceContext() {
            Dispose(false);
        }

        [ThreadStatic]
        private static ResourceContext _current_context;

        /// <summary>
        /// Контекст ресуров в текущем потоке
        /// </summary>
        public static ResourceContext Current {
            get {
                if (!IsInitialized)
                    throw new InvalidOperationException(«Context is not initialized.»);
                return _current_context;
            }
        }

        private readonly ResourceContext _previous_context;

        /// <summary>
        /// Инициализирован ли контекст
        /// </summary>
        public static bool IsInitialized {
            get {
                return !ReferenceEquals(null, _current_context);
            }
        }

        private readonly SqlConnection _connection;

        public SqlConnection Connection {
            get {
                if (_connection.State == System.Data.ConnectionState.Closed
                    || _connection.State == System.Data.ConnectionState.Broken)
                    _connection.Open();
                return _connection;
            }
        }

        private void Dispose(bool disposing) {
            if (disposing) {
                if (ReferenceEquals(this, _current_context)) {
                    _current_context = _previous_context;
                    // TODO: очистка ресурсов…
                    _connection.Dispose();
                } else {
                    throw new InvalidOperationException(«Context can’t be closed here.»);
                }
            }
        }

        private bool _disposed = false;

        public void Dispose() {
            if (!_disposed) {
                Dispose(true);
                _disposed = true;
                GC.SuppressFinalize(this);
            }
        }
    }

    class Program {
        static void Main(string[] args) {
            using (new ResourceContext(«bla bla bla»)) {
                // первое обращение к контексту за соединением
                // приведет к открытию соединения с БД:
                // ResourceContext.Current.Connection
            }
        }
    }
}

DotNetFunda.com

Online: 890

  • Wait Loading …

Posted by Rrana under ASP.NET on 9/9/2011 | Points: 10 | Views : 2470 | Status : [Member] | Replies : 3

Hi,

I am getting error like this:===

Internal .Net Framework Data Provider error 1.

======================

Below is my code =================

#region DESTRUCTOR

~clsDBAccess()
{

if (dbCon.State == ConnectionState.Open)
dbCon.Close(); ****************************i am getting error here
dbCon.Dispose();

if (dbCmd != null)
{
dbCmd.Dispose();
}
if (dbAdp != null)
{
dbAdp.Dispose();
}
}

#endregion

===========================

Thanks in Advance

Sucharitha Goud

Bank Of America..


Responses

Posted by: Vuyiswamb
on: 9/9/2011 [Member] [MVP] [Administrator] NotApplicable
| Points: 25

Up

0
Down

What is the Error ?

Thank you for posting at Dotnetfunda

[Administrator]

Rrana, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rrana
on: 9/9/2011 [Member] Starter
| Points: 25

Up

0
Down

Hi Vuyiswamb,

Thanks for your response ,

Error is

Internal .Net Framework Data Provider error 1.

Sucharitha Goud

Bank Of America..

Rrana, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Vuyiswamb
on: 9/9/2011 [Member] [MVP] [Administrator] NotApplicable
| Points: 25

Up

0
Down

ok that is not a Complete Error , copy the whole Error and post it here or create a screenshot and attach it.

Thank you for posting at Dotnetfunda

[Administrator]

Rrana, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response

Понравилась статья? Поделить с друзьями:
  • Internal msi error installer terminated prematurely
  • Internal kraken decompression error
  • Internal json rpc error что это
  • Internal json rpc error metamask ошибка
  • Internal exception java net sockettimeoutexception read timed out как исправить