C# 线程安全事件调用的带反射的盲转换
我正在编写一个大量使用线程的类库,我希望将线程安全引入类库,而不是让开发人员自己来实现线程安全 我有一件事C# 线程安全事件调用的带反射的盲转换,c#,thread-safety,inversion-of-control,invoke,C#,Thread Safety,Inversion Of Control,Invoke,我正在编写一个大量使用线程的类库,我希望将线程安全引入类库,而不是让开发人员自己来实现线程安全 我有一件事 public delegate void OnPostHandler(); public event OnPostHandler OnPost; 和一种方法 public void FireEvent() { Delegate[] delegate_list = OnPost.GetInvocationList(); foreach (OnPostHandler d in
public delegate void OnPostHandler();
public event OnPostHandler OnPost;
和一种方法
public void FireEvent() {
Delegate[] delegate_list = OnPost.GetInvocationList();
foreach (OnPostHandler d in delegate_list)
{
//detect if d.Target is a System.Windows.Forms.Control
Type formType = Type.GetType("System.Windows.Forms.Control, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
if(formType != null) {
//need to cast d.Target to System.Windows.Forms.Control WITHOUT referencing System.Windows.Forms.Control
if(d.Target.InvokeRequired) {
d.Target.Invoke(d);
} else {
d();
}
} else {
d();
}
}
}
在firevent
中,我想将d.Target
强制转换为System.Windows.Forms.Control
,而不将System.Windows.Forms.Control
作为代码中的指定强制转换,如果可能,我希望使用formType
完成此操作,这样我就不会被迫自己链接表单程序集,因为这不是库的要求,也不必这样做
或者,有没有更好的方法来完成我正在尝试做的事情?使用界面。它位于
系统
中,由系统、Windows、Forms、Control
使用界面实现。它位于系统
中,由系统.Windows.Forms.Control
实现。通过反射,您可以:
Delegate[] delegate_list = OnPost.GetInvocationList();
Type formType = Type.GetType("System.Windows.Forms.Control, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
var invokeRequiredProp = formType.GetProperty("InvokeRequired");
foreach (OnPostHandler d in delegate_list)
{
if(formType != null) {
var invokeRequired = invokeRequiredProp.GetValue(d.Target, null);
if (invokeRequired) {
formType.GetMethod("Invoke").Invoke(d.Target, new object[]{d});
}
else {
d();
}
} else {
d();
}
}
GetMethod
和GetProperty
方法可能需要BindingFlags
参数
没有反射,您可以使用ISynchronizeInvoke
Delegate[] delegate_list = OnPost.GetInvocationList();
foreach (OnPostHandler d in delegate_list)
{
var form = d.Target as ISynchronizeInvoke;
if(form != null && form.InvokeRequired) {
form.Invoke(d);
}
else {
d();
}
}
通过反射,您可以:
Delegate[] delegate_list = OnPost.GetInvocationList();
Type formType = Type.GetType("System.Windows.Forms.Control, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
var invokeRequiredProp = formType.GetProperty("InvokeRequired");
foreach (OnPostHandler d in delegate_list)
{
if(formType != null) {
var invokeRequired = invokeRequiredProp.GetValue(d.Target, null);
if (invokeRequired) {
formType.GetMethod("Invoke").Invoke(d.Target, new object[]{d});
}
else {
d();
}
} else {
d();
}
}
GetMethod
和GetProperty
方法可能需要BindingFlags
参数
没有反射,您可以使用ISynchronizeInvoke
Delegate[] delegate_list = OnPost.GetInvocationList();
foreach (OnPostHandler d in delegate_list)
{
var form = d.Target as ISynchronizeInvoke;
if(form != null && form.InvokeRequired) {
form.Invoke(d);
}
else {
d();
}
}