Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling new SqlConnection() hangs program

This one has me stumped. I'm not even trying to connect to a database. When this code gets to the line where I instantiate a new SqlConnection object, it just hangs there, not throwing an exception or anything. I've tried compiling it for 2.0. 3.5 and 4.0, and they all hang. Of course it works on my machine and yours, too. But I'm trying to run this code on a Windows Server 2008 x64 server, and it won't budge.

// example.cs
using System;
using System.Data;
using System.Data.SqlClient;

public class MainClass {
    public static void Main(string[] args) {
        Console.WriteLine("start");
        SqlConnection conn = new SqlConnection(); // hangs here
        Console.WriteLine("finish");              // never makes it here.
    }
}

compilation (2.0): c:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe example.cs

like image 242
CrackingWise Avatar asked Dec 06 '11 23:12

CrackingWise


2 Answers

It's probably a broken performance counter which is the issue. I had this problem and I used Procmon to detect what happened. My .NET application hanged when it came to loading the registry keys for the performance monitor ".NET Data Provider for SqlServer"

I unloaded the counter with the following command to get it working:

unlodctr ".NET Data Provider for SqlServer"
like image 106
Jonas Lindau Avatar answered Sep 19 '22 22:09

Jonas Lindau


Your installation have to be broken. The code doesn't really do anything vital at all, so there is no reason to hang there.

The SqlConnection constructor does this:

public SqlConnection() {
  this.ObjectID = Interlocked.Increment(ref SqlConnection._objectTypeCount);
  base();
  GC.SuppressFinalize(this);
  this._innerConnection = DbConnectionClosedNeverOpened.SingletonInstance;
}

So, it increases a variable, copies it into a property, calls the base constructor, removes the object from the finaliser queue, and copies a reference. That's all.

The base (DbConnection) constructor does this:

protected DbConnection() {
}

So, there is nothing in here that actually does anything at all related to an actual database connection. All that is done when you actually open a connection.

Your program might just as well be hanging after the first Console.WriteLine call, and not even get as far as creating the SqlConnection object.

like image 33
Guffa Avatar answered Sep 19 '22 22:09

Guffa