C# 异步回调请问这样有意义吗
- C# code
namespace ConsoleApplication1{ class Program { public delegate string TakesAwhileDel(int data,int ms); static void Main(string[] args) { TakesAwhileDel dl = TakesAwhile; dl.BeginInvoke(1, 6000, AsyncCallbackImpl, dl); System.Threading.Thread.Sleep(1000); Console.ReadLine(); } public static void AsyncCallbackImpl(IAsyncResult ar) { TakesAwhileDel dl = ar.AsyncState as TakesAwhileDel; string re = dl.EndInvoke(ar); Console.WriteLine("结果{0}", re); //TakesAwhileDel d2 = TakesAwhile; dl.BeginInvoke(1, 6000, AsyncCallbackImpl, dl); } static string TakesAwhile(int data, int ms) { Console.WriteLine("开始调用"); System.Threading.Thread.Sleep(ms); Console.WriteLine("完成调用"); string str = "测试成功"; return str; } }}
功能上需要不停的获取网页某一信息来判断,网上说异步比多线程性能上要好些,想这样写但感觉有点不像呢,请问这样写对吗?
[解决办法]
多线程可以构建异步模式,多线程是材料,异步模式是组织方式,把红木可以做成太师椅,但如果说太师椅比红木好,就有点不搭界。
推荐给你几篇文章吧
http://blog.csdn.net/etudiant6666/article/details/7449040
http://blog.sina.com.cn/s/blog_72ed17450100tx2l.html
[解决办法]
对于你的代码,在异步处理时,要注意尽可能少的占用时间,即通过各个线程的信号沟通,实现事物的处理。比如你发出异步任务后,就不好使用固定的等待时间(因为这样的话,你的业务处理完了,主线程还在等待,没处理完,主线程也可能强制结束了),而最好由回调函数去释放你的阻塞等待。
- C# code
namespace ConsoleApplication1{ class Program { public delegate string TakesAwhileDel(int data,int ms); ManuResetEvent _BlockEvent=new ManuResetEvent(false); static void Main(string[] args) { TakesAwhileDel dl = TakesAwhile; dl.BeginInvoke(1, 6000, AsyncCallbackImpl, dl); _BlockEvent.WaitOne(); Console.ReadLine(); } public static void AsyncCallbackImpl(IAsyncResult ar) { TakesAwhileDel dl = ar.AsyncState as TakesAwhileDel; string re = dl.EndInvoke(ar); Console.WriteLine("结果{0}", re); _BlockEvent.Set(); } static string TakesAwhile(int data, int ms) { Console.WriteLine("开始调用"); System.Threading.Thread.Sleep(ms); Console.WriteLine("完成调用"); string str = "测试成功"; return str; } }}