private void Delcalmethod(MethodInvoker method)
{
if (InvokeRequired)
Invoke(method);
else
method();
}
private delegate int getMax(); //委托
getMax delegateMax;
private int mathbig() //方法
{
List<int> list = new List<int>() { 1, 100, 2, 3, 22, 99, 1000, 23, 4000, 44, 300, 3000 };
int temp = 0; //中间介质
var arr = list.Select(x => x).ToArray();
for (int i = arr.Length - 1; i >0; i--)
{
for (int j = 0; j < i; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr[arr.Length - 1];
}
********************** 方法调用*****************************
private void button1_Click(object sender, EventArgs e)
{
delegateMax = mathbig;
IAsyncResult ar = delegateMax.BeginInvoke(CompleteCallback, "异步执行完毕");
while (!ar.IsCompleted)
{
txtAsyncResult.AppendText("继续算...");
}
txtAsyncResult.AppendText("计算其他方法");
txtAsyncResult.AppendText("等待主方法计算完毕");
}
private void CompleteCallback(IAsyncResult iar)
{
Delcalmethod(() =>
{
int result = delegateMax.EndInvoke(iar);
txtAsyncResult.AppendText(result.ToString());
MessageBox.Show(iar.AsyncState as string); //此方法执行异步状态
});
}