I am trying to use asynchronous calls to save a database and I have realised my understanding of how things work may be incorrect. I have done a number of google searches but it hasn’t helped to reduce my confusion
What I have is similar to the following:
private delegate bool MyDelegate();
private void ExportButton_Click(object sender, EventArgs e)
{
// Disable button
exportButton.Enabled = false;
MyDelegate deleg = ExportDatabase;
// Begin the export
deleg.BeginInvoke(ExportDatabaseCallback, null);
}
public bool ExportDatabase()
{
// Do Stuff
return true;
}
private void ExportDatabaseCallback(IAsyncResult ar)
{
// Enable button
Invoke((MethodInvoker)delegate { exportButton.Enabled = true; });
MessageBox.Show("Exporting Database complete");
}
Now, looking at other pages seems to indicate in my BeginInvoke I should do this as: deleg.BeginInvoke(new AsyncCallback(ExportDatabaseCallback), null); but what I have works, so am I doing something wrong here?
the other thing is that I believe in my callback I am supposed to call EndInvoke() as other stackoverflow questions state it is not optional. But then in other places it seems it is? But most comments I can find are from 2009 and I don’t know if things have changed since then. Is this the only way to get the bool from the ExportDatabase?
is just the old, longer way to create a delegate. Your code does exactly the same.
And
EndInvoke()is sometimes optional but you don’t want to know when and when not. Just call it, and you’re always right.