In the interface program, often need some data classes, interface elements through the binding and other ways to display the data, however, because the UI thread is not thread-safe, it is generally necessary to invoke the interface control via Invoke. For Data-bound bindinglist, however, The Listchang event cannot be responded to, resulting in controls such as the backend grid not updating Data. Waste a great effort finally found a uibindinglist, to achieve synchronization of thread data!
Using System;Using system.componentmodel;Using system.threading;Using System.Windows.Forms;Namespace tempforms{PublicPartialClass Form1:form {Public Form1 () {initializecomponent (); Initial (); }Private uibindlist<Int> _list;Privatevoid Initial () {_list =New uibindlist<int> {synchronizationcontext = synchronizationcontext.current}; Bindingsource1.datasource = _list;New Thread (() = {while (True) {thread.sleep (1000);var newitem = DateTime.Now.Second; _list. ADD (newitem); Thread.Sleep (1000); _list. Remove (newitem); }}) {isbackground =True,}. Start (); } }///<summary>Extend BindingList to prevent adding, deleting items automatically update the interface without the "cross-threading interface control" exception///</summary>Class Uibindlist<t>: Bindinglist<t> {///<summary>Interface Synchronization Context///</summary>Public SynchronizationContext SynchronizationContext {GetSet }///<summary> ///use This method to perform all operation context-sensitive Operations. Span class= "comment" >///</summary> Private void excute (action action, object state = Null) {if (synchronizationcontext = = null) Action (); else synchronizationcontext.post (d = = Action (), state);} public new void Add (T item) {excute (() = base. ADD (item)); } public new void Remove (T item) {excute (() = Span class= "keyword" >base. Remove (item)); } }}