我正在尝试使用System.Windows.Forms.Design.StringCollectionEditor.通过Windows Forms属性网格公开我的List类成员我的问题是关于线程安全的。
[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 (或类似的东西)并保持线程安全的最好方法是什么?
发布于 2013-02-27 05:16:44
来自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;
}https://stackoverflow.com/questions/14659161
复制相似问题