here ,we need to clear something AsynCallBack in .netFrameWork even implements the mutilple threads or just use delegate to pack some certain functions. this is the key we clear up the problem; first we should discuss the AsyncallBack: i take the SqlDataReader for example;
look at the followed relative functions or objects:
1.AsynCallBack
2.BeginExecuteReader
3.IAsyncResult
use :AsynCallBack asyncall = new AsynCallBack(packingFuc);
sqlCommand.BeginExcuteReader(asynCall,IAsyncResult ar)
packingFuc(IAsyncResult ar){sqlCommand.EndExecuteReader(ar)}
looking over the declaration of the class AsynCallBack,we can find it is just a delegate with one parameter,so we can have a guess how it would be declared:
public delegage void AsyncallBack(IAsyncResult result)
referring to IAsyncResult,we should think about its elements if the elements need to be evaluated by programmers,and which need it?
i have a process :
protected void btn_Clicked(object sender,EventArgs e)
{
AsyncCallback callback = new AsyncCallback(searchDataFromDB);
string sqlExcuteCmd = "select * from sp";
SqlCommand cmd = mydbtools.UseSqlDataReaderToReadData(sqlExcuteCmd);
cmd.BeginExecuteReader(callback, cmd);
}
private void searchDataFromDB(IAsyncResult ar)
{
ArrayList list = new ArrayList();
SqlCommand cmd = (SqlCommand)ar.AsyncState;
SqlDataReader reader = cmd.EndExecuteReader(ar);
if (reader.HasRows)
{
foreach (DbDataRecord record in reader)
{
list.Add(record);
}
}
reader.Close();
this.dataGridView1.Invoke(new MethodInvoker( delegate{ dataGridView1.DataSource = list; }));
}
here ,i want to indicate something else :new MthodInvoker(),if we use the delegate directly,the complie tool will pop up us the error message:the anonymous delegate method can't transfer into System.Delegate ,why not the delegate is the type of System.Delegate, for this error ,we can get two causes to explain it
first there must be multiple objects have the same methods,the compile tool is confusing,it can't be due to take which one it should be ,so we have to do with it explicitly;
second you use an error method; this is why thread can use the anonymous delegate but control.inovke not;
and DataGridView can bind the arraylist
and delegate can pack one certain funcitions to a class,so we can use the instance like a object :
delegate void MyDelegate();
MyDelegate objectDel = new MyDelegate(MyFunc);
objectDel.BeginInvoke(string,AsynCallBack,object);
this is why we need declare a delegage to AsynCallBack when we want to use asynchronism,and not to use delegate and thread directly because there are a lot of class and interface in clr inheriting the IAsyncResult or something else;
and i doubt the endInvoke just working on changing state of object of being IAsyncResult;