Clossing sqlconnection

R

Robert Bravery

HI all,

I'm trying my hand at async processing. I have the following, my question is
where do I close the sql connection. Do I close it in this function or in
the ExecCallback function, if so where, after the endexecutereader call?????

Thanks

Robert



string constr2 = ReadConFile("conString.txt".Trim()); //"Data
Source=ROBERT\\SQLExpress;Initial Catalog=Genport;Integrated Security=True;
Connection Timeout = 0;Asynchronous Processing=true";
constr2 += "; Connection Timeout = 0;Asynchronous Processing=true";
SqlConnection con2 = new SqlConnection(constr2);
SqlCommand cmd3 = new SqlCommand();
cmd3.Connection = con2;
cmd3.CommandType = CommandType.Text;
con2.Open();
toolStripStatusLabel1.Text = "Importing Data into table" + ", Please Wait...
";
this.Update();
cmd3.CommandText = cmdstr;
cmd3.CommandTimeout = 0;
AsyncCallback callback = new AsyncCallback(ExecCallback);
cmd3.BeginExecuteReader(callback, cmd3);
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

You close the connection when you are done reading from the DataReader.
If you close the connection before that, the DataReader doesn't work any
more.
 
N

Nicholas Paldino [.NET/C# MVP]

Robert,

You would do it after you cycle through the data reader in the callback
from BeginExecuteReader.

You will want to wrap the call to EndExecuteReader in a try/catch block,
so that if it throws, you can dispose of the connection correctly still (you
can get the connection from the command).

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

P.S. You shouldn't be keeping your connection string in a text file like
that. Place it in the config file for the application, as the framework has
support for getting information like this through the classes in the
System.Config namespace.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top