0

我正在尝试使用 System.Windows.Forms.Design.StringCollectionEditor 通过 Windows 窗体属性网格公开我的 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 (或类似的东西)并保证线程安全的最佳方法是什么?

4

1 回答 1

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;
}
于 2013-02-26T21:16:43.870 回答