2013-02-02 48 views
0

我想通過使用System.Windows.Forms.Design.StringCollectionEditor的Windows窗體屬性網格公開我的List類成員。我的問題是關於線程安全性使用StringCollectionEditor與線程安全列表

[Editor("System.Windows.Forms.Design.StringCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))] 

public List<string> EventLogSources { 
     get { 
      lock (lockObj) { 
       return eventLogSources; 
      } 
     } 
} 

顯然這不是線程安全的,因爲多線程可以獲取引用並更新它。那麼使用StringCollectionEditor(或類似的東西)並且線程安全的最佳方式是什麼?

+0

基本上,看它的另一種方式是,我需要提供真實eventLogSources列表中StringCollectionEditor(副本不會做因爲那樣它將不可編輯)。但同時我需要保留其他客戶端代碼進行編輯。 –

+0

更簡單的事實是,只有用戶需要更新列表中的字符串,並且所有其他線程都會讀取數據。因此,如果在幕後,StringCollectionEditor不會修改數組的內容,而只是將新數組(包含新的/修改的內容)分配給EventLogSources屬性,那麼我相信我應該沒問題。我試圖關閉這個問題,但我不明白的是爲什麼StringCollectionEditor不需要在EventLogSources屬性上設置setter –

回答

0

http://mastersact.blogspot.com/2007/06/string-collection-editor-for-property.html代碼看起來像它會做的伎倆:

public override object EditValue(ITypeDescriptorContext context, 
IServiceProvider serviceprovider, object value) 
{ 
if (serviceprovider != null) 
{ 
mapiEditorService = serviceprovider 
.GetService(typeof(IWindowsFormsEditorService)) as 
IWindowsFormsEditorService; 
} 

if (mapiEditorService != null) 
{ 
StringCollectionForm form = new StringCollectionForm(); 

// Retrieve previous values entered in list. 
if (value != null) 
{ 
List stringList = (List)value; 
form.txtListValues.Text = String.Empty; 
foreach (string stringValue in stringList) 
{ 
form.txtListValues.Text += stringValue + "\r\n"; 
} 
} 

// Show Dialog. 
form.ShowDialog(); 

if (form.DialogResult == DialogResult.OK) 
{ 
List stringList = new List(); 

string[] listSeparator = new string[1]; 
listSeparator[0] = "\r\n"; 

string[] listValues = form.txtListValues.Text 
.Split(listSeparator, StringSplitOptions.RemoveEmptyEntries); 

// Add list values in list. 
foreach (string stringValue in listValues) 
{ 
stringList.Add(stringValue); 
} 

value = stringList; 
} 

return value; 
} 

return null; 
}