首页 新闻 会员 周边

为什么输出结果是4,不是11,还有在CallbackMethod2()中m=11,为什么一调用就是4? 麻烦大神了,谢谢~~

0
悬赏园豆:5 [已解决问题] 解决于 2014-12-02 12:09

public delegate int sum(int a, int b);//定义一个执行加法的委托
public class number
{
public int m=4;//定义一个实现此委托签名的方法
public int numberAdd(int a, int b)
{
int c = a + b;
return c;
} //定义一个与.net framework定义的asynccallback委托相同的回调函数
public void CallbackMethod2(IAsyncResult ar2)
{
sum s = (sum)ar2.AsyncState;
int number = s.EndInvoke(ar2);
this.m = number;
}
}
static void Main(string[] args)
{
number num = new number();
sum numberadd = new sum(num.numberAdd);
AsyncCallback numberback = new AsyncCallback(num.CallbackMethod2);
numberadd.BeginInvoke(2, 9, numberback, numberadd);
Console.WriteLine(num.m);
Console.ReadLine();
}

六年约定三年承诺的主页 六年约定三年承诺 | 初学一级 | 园豆:101
提问于:2014-12-01 23:26
< >
分享
最佳答案
1

BeginInvoke 这个是异步的啊 昏死

在你执行完之前就执行了这个了Console.WriteLine(num.m);

你在 Console.WriteLine(num.m);前加上

thread.sleep(100)

static void Main(string[] args)
{
number num = new number();
sum numberadd = new sum(num.numberAdd);
AsyncCallback numberback = new AsyncCallback(num.CallbackMethod2);
numberadd.BeginInvoke(2, 9, numberback, numberadd);
thread.sleep(100);
Console.WriteLine(num.m);
Console.ReadLine();
}
收获园豆:5
小眼睛老鼠 | 老鸟四级 |园豆:2731 | 2014-12-02 00:25

可以了,谢了~~

六年约定三年承诺 | 园豆:101 (初学一级) | 2014-12-02 12:09
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册