範例參考QPUnitMain
1.宣告
public delegate void dg_onCommandExec(string sLoop,CobjState objCmd, string result);
public event dg_onCommandExec onCommandExec;
dg_onCommandExec link_dg_onCommandExec;
2. 連接 宣告與實做
link_dg_onCommandExec = do_dg_onCommandExec;
3. 在程式中呼叫CallCommandExec(objCmd, result);
4. 建立event 的 非同步的Invoke,並且定義所執行的實做基礎工作
void CallCommandExec(CobjState objCmd, string result)
{
if (onCommandExec != null)
{
string sLoop = objCmd.objString.Substring(objCmd.objString.IndexOf(':') + 1, objCmd.objString.Length - objCmd.objString.IndexOf(':') - 1);
//在元件的返回thread safe 事件做法,必須利用event的ISynchronizeInvoke來做到,所以caller就可以直接承接
System.ComponentModel.ISynchronizeInvoke aSynch = onCommandExec.Target as System.ComponentModel.ISynchronizeInvoke;
if (aSynch != null && aSynch.InvokeRequired)
aSynch.Invoke(link_dg_onCommandExec,new object[] { sLoop, objCmd, result});
else
onCommandExec.Invoke(sLoop, objCmd, result);
}
}
5. 實做基礎工作
void do_dg_onCommandExec(string sLoop, CobjState objCmd, string result)
{
if (onCommandExec != null)
{
onCommandExec.Invoke(sLoop, objCmd, result);
}
}
http://www.cnblogs.com/magic-cube/archive/2012/08/03/2622159.html
http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/2bc7e006-5218-4abc-a3db-561f141704bd
System.EventHandler Connected;
private void RaiseConnected()
{
// Get local event for thread safety purposes
EventHandler handler = Connected;
if (handler != null)
{
foreach (EventHandler singleCast in handler.GetInvocationList())
{
ISynchronizeInvoke syncInvoke = singleCast.Target as ISynchronizeInvoke;
try
{
if (syncInvoke != null && syncInvoke.InvokeRequired)
{
// Invokie the event on the main thread
syncInvoke.Invoke(handler, new object[] { this, null });
}
else
{
// Raise the event
singleCast(this, null);
}
}
catch
{
}
}
}
}