111,128
社区成员
发帖
与我相关
我的任务
分享using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BeginInvoke112
{
class Program
{
//定义一个委托
public delegate int sum(int a, int b);
//定义一个类
public class number
{
public int m =4;
//定义一个和委托一样签名的方法
public int numadd(int a, int b) {
return a + b;
}
//定义一个与AsyncCallback委托对应的回调方法
public void Callback(IAsyncResult ar)
{
sum s = (sum)ar.AsyncState;
m= s.EndInvoke(ar);
}
}
static void Main(string[] args)
{
number n = new number();
sum s1 = new sum(n.numadd);//把S1这个委托指向n.numadd方法
AsyncCallback async = new AsyncCallback(n.Callback);//回调方法把n.callback放入
s1.BeginInvoke(55, 33, async, s1);
Console.WriteLine("this sum is :{0}",n.m);
Console.ReadKey();
}
}
}
beginInvoke(null,null)这里不太明白了。
我看得还真是10年的书,看样子这书不怎么行!谢谢大师的指导,class Program
{
public class number
{
public int m = 4;
public void numadd(int a, int b)
{
m = a + b;
Console.WriteLine("this sum is :{0}", m);
}
}
static void Main(string[] args)
{
number n = new number();
ThreadPool.QueueUserWorkItem(h => n.numadd(55, 33));
Console.ReadKey();
}
}
或者
class Program
{
public class number
{
public int m = 4;
public void numadd(int a, int b)
{
m = a + b;
Console.WriteLine("this sum is :{0}", m);
}
}
static void Main(string[] args)
{
number n = new number();
new Thread(() => n.numadd(55, 33)).Start();
Console.ReadKey();
}
}
或者
class Program
{
public class number
{
public int m = 4;
public void numadd(int a, int b)
{
m = a + b;
Console.WriteLine("this sum is :{0}", m);
}
}
static void Main(string[] args)
{
number n = new number();
new Action(() => n.numadd(55, 33)).BeginInvoke(null, null);
Console.ReadKey();
}
}
可能你学的是10几年前的 c# 的书。怎么你写出那么繁琐、累赘的代码呢?不累吗?class Program
{
//定义一个委托
public delegate int sum(int a, int b);
//定义一个类
public class number
{
public int m = 4;
//定义一个和委托一样签名的方法
public int numadd(int a, int b)
{
return a + b;
}
//定义一个与AsyncCallback委托对应的回调方法
public void Callback(IAsyncResult ar)
{
sum s = (sum)ar.AsyncState;
m = s.EndInvoke(ar);
Console.WriteLine("this sum is :{0}", m);
}
}
static void Main(string[] args)
{
number n = new number();
sum s1 = new sum(n.numadd);//把S1这个委托指向n.numadd方法
AsyncCallback async = new AsyncCallback(n.Callback);//回调方法把n.callback放入
s1.BeginInvoke(55, 33, async, s1);
Console.ReadKey();
}
}
Sleep 是很垃圾的,误导自己的。原本是要获得计算结果,只要产生结果就立刻显示结果。那么你如果写 Sleep 语句,要故意阻塞多久?付出这个代价还有什么必要使用多线程呢?
纠结 Sleep、“度太快了”,这都是错误的逻辑。你要从逻辑上搞明白流程(只要有结果就立刻打印结果,没有一毫秒延迟),就能搞懂 Sleep 是多么不靠谱的东西。。 number n = new number();
sum s1 = new sum(n.numadd);//把S1这个委托指向n.numadd方法
AsyncCallback async = new AsyncCallback(n.Callback);//回调方法把n.callback放入
s1.BeginInvoke(55, 33, async, s1);
Thread.Sleep(1000);//加入这句让主线程休眠
Console.WriteLine("this sum is :{0}",n.m);
Console.ReadKey();
这样的结果就是对的。书上的 Console.WriteLine("this sum is :{0}",n.m);这个代码是分了二段
Console.WriteLine("this sum is :{0}");
Console.WriteLine(,n.m);
所以有空执行完是这个意思吧。
为什么Endinvoke不是执行完后返回吗?为什么还没有返回就输出了?是速度太快了导致还没有执行回调就输出了?