这个示例是在Winform里做的,大家可以参考:
- //定义声明委托
- private delegate string returnresult(int i, long b);
- /// <summary>
- /// 同步执行事件
- /// </summary>
- private void button3_Click(object sender, EventArgs e)
- {
- returnresult sl = sss;
- string ssa = sl.Invoke(0, 1000000101);//只有等待
- MessageBox.Show(ssa);
- }
- private string sss(int a, long b)
- {
- long s = 0;
- for (long o = a; o < b; o++)
- {
- s += o;
- }
- return s.ToString().Trim();
- }
- /// <summary>
- /// 异步执行时间
- /// </summary>
- private void button5_Click(object sender, EventArgs e)
- {
- returnresult dd = sss;
- AsyncCallback sas = new AsyncCallback(asiresult);
- dd.BeginInvoke(0, 1000000101, sas, dd);//照样运行
- MessageBox.Show("照样运行!!!");
- }
- /// <summary>
- /// 回调函数
- /// </summary>
- /// <param name="asa"></param>
- private void asiresult(IAsyncResult asa)
- {
- returnresult aass = asa.AsyncState as returnresult;
- MessageBox.Show(aass.EndInvoke(asa));
- }