这是调用同步异步方式的正确方法? [英] Is this a proper way of calling synchronous methods asynchronously?

查看:143
本文介绍了这是调用同步异步方式的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是用code是这样的:

  handler.Invoke(发件人,E);

不过,与code中的问题是,它是同步的,它确实做到了是更新GUI。这是没有必要的服务器等待它完成,因此应使异步

我真的不希望使用的BeginInvoke和EndInvoke因为一个回调方法,没有必要在这种情况下。

这是一个合适的选择?

  Task.Factory.StartNew(()=> handler.Invoke(发件人,E));


解决方案

你做的是罚款的方式,另一种方式来做到这一点,在.NET 3.5的工作原理是使用线程池类,而不是

  ThreadPool.QueueUserWorkItem(新WaitCallback((A)=> handler.Invoke(发件人,E)))

此外,如果处理程序恰好是从控制来源,你被允许打电话的BeginInvoke没有相应的EndInvoke。

I was using code like this:

handler.Invoke(sender, e);

But the problem with that code is that it is synchronous and all it really does is update the GUI. It is not necessary for the server to wait for it to complete so it should be made asynchronous.

I don't really want to use BeginInvoke and EndInvoke because a callback method is not necessary in this case.

Is this a suitable alternative?

Task.Factory.StartNew(() => handler.Invoke(sender, e));

解决方案

The way you did it is fine, another way to do this that works on .NET 3.5 is using the ThreadPool class instead

ThreadPool.QueueUserWorkItem(new WaitCallback((a) => handler.Invoke(sender, e)))

Also if handler happens to be a derived from control, you are allowed to call BeginInvoke without a corresponding EndInvoke.

这篇关于这是调用同步异步方式的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆