日期:2014-05-17  浏览次数:21132 次

关于多线程和委托
这是一个对于图片的动画程序,
  ThreadStart threadMethod;
  threadMethod = ShowImmediately;
  switch (show)
  {
  case "立即显示":
  // ShowImmediately(speed, delay);
  // ShowTest(speed, delay);
  threadMethod = ShowImmediately;
  break;
  case "清屏":
  threadMethod = ShowClear;
  break;
  case "左移":
  threadMethod = ShowLeftShift;
  break;
  case "右移":
  threadMethod = ShowRighShift;
  break;
  case "上移":
  threadMethod= ShowUpShift;
  break;
  case "下移":
  threadMethod = ShowDownShift;
  break;
  case "中心展开":
  threadMethod = ShowCentreExpand;
  break;
  case "中心合拢":
  threadMethod = ShowCentreFold;
  break;
  case "上下合拢":
  threadMethod = ShowUpDown;
  break;
  case "上下展开":
  threadMethod = ShowUpToDown;
  break;
  case "左右合拢":
  threadMethod = ShowRightLeft;
  break;
  case "左右展开":
  threadMethod = ShowRightToLeft;
  break;
  case "横百叶窗":
  threadMethod = ShowHorizontalWindows;
  break;
  case "竖百叶窗":
  threadMethod = ShowVerticalWindows;
  break;
  case "淡入":
  threadMethod = ShowFadeIn;
  break;
  case "淡出":
  threadMethod = ShowFadeOut;
  break;
  default:
  break;
  }
  Thread drawThread = new Thread(threadMethod);
  //System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//防止出现 线程间操作无效:
  drawThread.IsBackground = true; // 设为后台线程,避免该线程未结束时退出主线程而引发异常
  drawThread.Start();
用的时候系统爆出异常,提示线程间操作无效,从不是创建控件的线程访问他,我加上System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
这行代码就行了,但网上说不安全,最好用委托,想请教下,委托的话代码怎么写,麻烦各位详细点,委托这一块不是很懂。

------解决方案--------------------
C# code

public delegate void  ShowImmediatelyEventHandler(int speed,int delay);
private void ShowImmediately(int speed,int delay)
{
    if(A.InvokeRequired)
{
   this.invoke(new ShowImmediatelyEventHandler(ShowImmediately));
}
else
{
//做显示的内容
}
}