开发者

How To Update A ListView From A WCF Service?

I have a WCF service hosted in a Windows Forms app开发者_开发知识库lication (.NET C# 4). This runs on it's own thread. When a method is called on the WCF service, I want to update a List (i.e. List) and then the ListView in the Form adds a row to the display.

What would be the best way to achieve this?


under windows, controls must be updated in the primary application or GUI thread and not from worker threads as you have suspected. the primary reason for this is that controls make use of the Windows Message Pump which must be processed by the primary thread.

to update a control from a non-UI thread you thread-marshal data from a worker thread to the UI thread; in .net this is an easy affair. you create a delegate callback method which is invoked via BeginInvoke() or Invoke() which are asynchronous and synchronous respectively.

myListBox.BeginInvoke(new MyDelegate(DelegateMethod), "hi there");

public void DelegateMethod(ListView myControl, string message)
{
   myControl.Items.Add (message);
}

depending on your performance needs, you may want to use BeginInvoke() to have the update done in the background as opposed to Invoke() which blocks the worker thread. one thing to consider though that if you do too many BeginInvoke() per time interval, it can hinder performance of your app as the Windows Message Pump is thrashed, not to mention some messages may be lost. realistically though, you would need to be doing quite a bit for this to occur and it goes hand-in-hand with any other requirement for performance.

hope all goes well

this article describes it further.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜