开发者

Is this a proper way of calling synchronous methods asynchronously?

开发者 https://www.devze.com 2023-04-10 04:49 出处:网络
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 th

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.


Calls to GUI are special in that they must always be done from the GUI thread. In your own words, handler.Invoke(sender, e) "updates the GUI", yet it is (probably) not executed from the GUI thread, so it not OK in its current form.

In WinForms, you'll need to wrap your task delegate into Control.Invoke (or forget about tasks and just use Control.BeginInvoke).

If WPF, you can wrap your task delegate into Dispatcher.Invoke (or just use Dispatcher.BeginInvoke without a task).


I'm not familiar with C# 4's Task class, but I know BeginInvoke works just fine without EndInvoke. I sometimes write code like this:

handler.BeginInvoke(sender, e, null, null);

Edit: I was mistaken. While EndInvoke is not necessary to cause the code to execute on a new thread, the documentation clearly states that EndInvoke is important.

0

精彩评论

暂无评论...
验证码 换一张
取 消