timer多线程异步请求数据(Task)

来源:互联网 发布:从淘宝上怎么买东西 编辑:程序博客网 时间:2024/06/05 04:32

//Timer不要声明成局部变量,否则会被GC回收
private static System.Timers.Timer timer = new System.Timers.Timer();


 public static void Main()
    {
        timer.Interval = 1000;
        timer.Elapsed += TimersTimerHandler;
        timer.Start();
    }
  private static void TimersTimerHandler(object sender, EventArgs args)
    {
       
      if (Interlocked.Exchange(ref inTimer, 1) == 0)
        {
Station();
         Interlocked.Exchange(ref inTimer, 0);
       }
    }

//获取站点信息

 public static void Station()

        {
            StationManage sm = new StationManage();
            List<Station> list = sm.Get();
            StationDetailManage sdm = new StationDetailManage();
            stationdetaillist = sdm.Get();
            int page = 1000;
            int count = list.Count();
            int num = count / page;
            if (count % page > 0)
            {
                num += 1;
            }
            List<object> listobj = new List<object>();
            for (int i = 0; i < num; i++)
            {
                int start = i * page;
                if (i == num - 1)
                {
                    int end = count - start;
                    List<Station> temp = list.GetRange(start, end);
                    listobj.Add(temp);
                }
                else
                {
                    List<Station> temp = list.GetRange(start, page);
                    listobj.Add(temp);
                }
            }
            ExecuteAllTask(GetStationResult, listobj);

        }

//Task执行方法

 public static void ExecuteAllTask(Action<object> method, List<object> listobj)
        {
            List<Task<bool>> listt = new List<Task<bool>>();
            listobj.ForEach(x => {
                var t = Task.Factory.StartNew(() =>
                {
                    method(x);
                    return true;
                });
                listt.Add(t);
            });
            Task.WaitAll(listt.ToArray());
        }

//取到数据后保存数据

  public static void GetStationResult(object obj)
        {

}

0 0
原创粉丝点击