首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

线程刷新超时有关问题,timeout

2013-11-09 
线程刷新超时问题,timeout做了个程序,建立了线程,每个线程里面有刷新数据的功能,也就是每10秒刷新一次,如

线程刷新超时问题,timeout
做了个程序,建立了线程,每个线程里面有刷新数据的功能,也就是每10秒刷新一次,如果3分钟这个线程没有刷新数据就重启这个线程,请问这个超时改怎么弄?


 public void Set_labelText(XmlNode strText) 
        {
            this.Invoke((Action<XmlNode>)delegate(XmlNode node)
            {
                StationData stationData = new StationData(node);
                //stationData.IsShow = false;
                Program.listStationList.Add(stationData);
                this.flowLayoutPanel1.BackColor = Color.Orange;
                Label lab = new Label();//实例一个label显示

                lab.Name = "lab" + stationData.CardFlagID.ToString();
                lab.AutoSize = false;
                lab.Size = new Size(280, 140);
                lab.BorderStyle = BorderStyle.Fixed3D;
                lab.Text = stationData.StatinName;
                lab.Font = new Font("宋体", 11);

                if (stationData.IsShow)
                {
                    lab.BackColor = Color.Green;
                }
                if (stationData.IsShow)
                {
                    System.Threading.Timer tim = new System.Threading.Timer(ti, stationData.CardFlagID, 0, 10000);
                    //超过0秒后,以及此后每隔10秒间隔,都会调用一次由TimerCallback(ShowDataToScreenStation)指定的委托。
                    //每隔10秒,刷新一次检测站数据
                    dicThread.Add(stationData.CardFlagID.ToString(), tim);
                    
                }
                this.flowLayoutPanel1.Controls.Add(lab);
            }, strText);
        }

超时 线程 timer
[解决办法]

class TimerController
{
     public readonly System.Timers.Timer Monitor;
     public TimerController()
     {
         this.Timers = new List<MyTimers>();
         this.Monitor = new System.Timers.Timer(1000);
         this.Monitor.Elapsed += Timer_Elapsed;
         this.Monitor.Start();
     }

     public List<MyTimer> Timers{get; private set;}

     //再放一个单独的Timer,用来监视这些工作线程的状态
     void Monitor_Elapsed(object sender,ElapsedEventArgs e)
     {
         var now = DateTime.Now;
         for(int i = Timers.Count - 1; i >= 0; i--)


         {
             var timer = Timers[i];
             if((now - timer.LastSignalTime).TotalSeconds >= 300 && !timer.DataRefreshed)
             {
                 timer.Stop();
                 timer.Start();
             }
         }
     }
}

class Form中
{
private TimerController timerController = new TimerController();

public void Set_labelText(XmlNode strText) 
{
    ……
    if (stationData.IsShow)
    {
         var timer = new MyTimer(10000);
         timer.Elapsed += RefreshData;
         timerController.Timers.Add(timer);   //改成字典也可以,注意Timers要作下同步,上面省去了
    }
}

void RefreshData(object sender, ElapsedEventArgs e)
{
  var timer = sender as System.Timers.Timer;
  try
  {
      timer.Stop();
      if(刷新数据成功) timer.LastRefreshTime = e.SignalTime; 这一步很关键    
  }
  finally
  {
      timer.Start();
  }
}

热点排行