日期:2014-05-18  浏览次数:20807 次

异步调用问题
我在写数据库程序时,希望能够将很多的结果一次返回,因而采用了异步调用,但在调用过程中,要么界面没有任何反应,要么有时出现下列错误:末处理INVALIDOPERATIONEXCEPTION 。不知何因,;界面只有一DATABINDVIEW1与BUTTON1。代码如下:请各位高手指点迷津,已经搞了几天了,都没有搞好。
BUTTON1单击:
dbrecordholder =new ArrayList();
  string connectstring = "asynchronous processing=true;Password=123;Persist Security Info=True;User ID=sa;Initial Catalog=demo;Data Source=127.0.0.1";
  using (SqlConnection testconnection = new SqlConnection(connectstring)) 
  {
  SqlCommand textcommand = new SqlCommand("select * from uname", testconnection);
  testconnection.Open();
  //SqlDataReader sqldr = textcommand.ExecuteReader(CommandBehavior.CloseConnection);
  //if (sqldr.HasRows)
  //{
  // foreach (DbDataRecord rec in sqldr)
  // {
  // dbrecordholder.Add(rec);
  // }
  //}
  //sqldr.Close();

  AsyncCallback callback = new AsyncCallback(datareaderisready);
  IAsyncResult asyncresult= textcommand.BeginExecuteReader(callback, textcommand);
  dataGridView1.DataSource = dbrecordholder;
  bindingSource1.DataSource = dbrecordholder;
  bindingNavigator1.BindingSource = bindingSource1;
datareaderisready过程:
 private void datareaderisready(IAsyncResult result)
  {
  MessageBox.Show("result load complete", "i'm done");
  SqlCommand testcommand = (SqlCommand)result.AsyncState;
  //testcommand.Connection.Open();
  SqlDataReader sqldr = testcommand.EndExecuteReader(result);
  if (sqldr.HasRows)
  {
  foreach (DbDataReader rec in sqldr)
  {
  dbrecordholder.Add(rec);
  }
  }
  sqldr.Close();
  testcommand.Connection.Dispose();
  }

  跪求解决方法

------解决方案--------------------
using (SqlConnection testconnection = new SqlConnection(connectstring)) 

}
执行后连接已关闭。
 private void button1_Click(object sender, EventArgs e)
{
SqlConnection testconnection = new SqlConnection(connectstring);

SqlCommand textcommand = new SqlCommand("select * from Addr_First_Table", testconnection);
testconnection.Open();

AsyncCallback callback = new AsyncCallback(datareaderisready);
IAsyncResult asyncresult = textcommand.BeginExecuteReader(callback, textcommand);

}

 private void datareaderisready(IAsyncResult result)
{
// MessageBox.Show("result load complete", "i 'm done");
SqlCommand testcommand = (SqlCommand)result.AsyncState;
//testcommand.Connection.Open();
SqlDataReader sqldr = testcommand.EndExecuteReader(result);
if (sqldr.HasRows)
{


}
sqldr.Close();
}