So, why doesn't this ever make it to the callback function?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace sqlAsyncTesting {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
using (SqlConnection conn = new SqlConnection(@"Data Source = bigapple; Initial Catalog = master; Integrated Security = SSPI; Asynchronous Processing = true;")) {
conn.Open();
SqlCommand cmd = new SqlCommand(@"WAITFOR DELAY '00:03'; Select top 3 * from sysobjects;", conn);
IAsyncResult result = cmd.BeginExecuteReader(new AsyncCallback(HandleCallback), cmd, CommandBehavior.CloseConnection);
}
}
private void HandleCallback(IAsyncResult result) {
SqlDataReader dr;
SqlCommand _this = (SqlCommand)result.AsyncState;
if (result.IsCompleted) {
dr = _this.EndExecuteReader(result);
} else dr = null;
DataTable dt = new DataTable();
DataSet ds = new DataSet();
dt.Load(dr);
ds.Tables.Add(dt);
dr.Close();
Complete(ds);
}
private void Complete(DataSet ds) {
string output = string.Empty;
foreach (DataColumn c in ds.Tables[0].Columns) {
output += c.ColumnName + "\t";
}
output += "\r\n";
foreach (DataRow dr in ds.Tables[0].Rows) {
foreach (object i in dr.ItemArray) {
output += i.ToString() + "\t";
}
output += "\r\n";
}
}
}
}
Some points I noticed:
If you are facing the issue listed in point no. 5, you can use the following alternate solution implemented by using asynchronous delegates rather than the built-in BeginExecuteReader() and EndExecuteReader(). In the solution below too, the control will be immediately returned to the next line after the delegate is invoked, just like it happens in the case of BeginExecuteReader().
Alternate Solution:
I think the connection is being closed before the Reader could work...
Try changing it to...
By the way this code waits for 3 minutes? Because to pause for 3 seconds shouldn't it be WAITFOR DELAY '0:0:3'?