问个问题,c#中,运行起来一个winform程序,点击连接按钮,启动一个定时器,这个定时器每0.1秒去执行一个方法。在点击连接之后,我还想按其他按钮,执行其他方法,但由于定时器里面的方法正在运行,所以点击其他按钮,执行其他方法时比较卡,所以我想弄两个线程,一个线程去执行定时器的方法,一个线程执行其他按钮的方法,,,没学过c#的多线程,求帮忙,求思路。

解决方案 »

  1.   

    timer根本就不是线程,你先把这个概念顺过来你那种就要开 Thread
      

  2.   

    组件的Timer压根就不是多线程,纯粹的UI组件不卡才怪,很多都喜欢用这个,实质上这个效率差,且性能不佳用这个System.Threading.Timer 这个就是本质多线程,而且灵活,采用的是后台线程池线程操作。
    处理好可以解决界面卡的问题
      

  3.   

    我没说timer是线程啊。。timer当然不是线程啦。要是这点我不知道的话,那就没必要问这个问题了。我想在timer里面写一个线程
      

  4.   

    那就看回复System.Threading.Timer 是多线程
      

  5.   

    使用System.Threading.Timer:
     //注意!!!:
            //这个Timer必须使用全局变量,如果声明成局部变量的话,只会执行一次,就被GC回收了
            private System.Threading.Timer _timer = null;        private void MyMethod(object state)
            {
                //do something
            }
            private void StartTimer()
            {
                const int perid = 100;//100ms
                if (_timer == null) _timer = new Timer(MyMethod, null, 0, perid);
                else _timer.Change(0, perid);
            }
      

  6.   

    new System.Threading.Timer(showCarVideo, null, 0, perid);我是这样写的,showCarVideo是我的方法,为什么会报错呢?参数无效
      

  7.   

    new System.Threading.Timer(showCarVideo, null, 0, perid);我是这样写的,showCarVideo是我的方法,为什么会报错呢?参数无效
      

  8.   

    要使用这个timer,你的showCarVideo这个方法必须带一个(object obj)的参数,即便你不用,也必须要写喔。
      

  9.   


    类似的场景有两种:
    一种是每隔一段时间执行一次某个操作。
    另一种是执行一次操作后,间隔一段时间再执行下一次操作。
    第一种场景使用timer较佳,而第二种情况推荐使用
    while(true)
    {
    //DoSomething
    Thread.Sleep(100);
    }
    示例:
    一、使用timer
    private System.Threading.Timer _timer = null;//这个要使用个全局变量,代码不好看
    private void StartMyWork()
    {
    _timer = new Timer(MyMethod, null, 0, 100);
    }
    private void MyMethod(object obj)
    {
     /*DoSomething*/
       //如果在timer里面需要更新UI控件的话,由于这个timer不是在主线程中执行的因此要这样访问:
       this.Dispatcher.BeginInvoke(
           new Action(
           () =>
           {
               //这样更新UI
           }));
    }
    二、使用死循环
    private void StartMyWork()
    {
    Action loopAction = MyMethod;
    loopAction.BeginInvoke(null,null);
    }
    private void MyMethod()
    {
    while(true)
    {
    //DoSomething
    Thread.Sleep(100);
    }
    }
      

  10.   

    没用过,不过这几天玩线程,是否可以在定时器中直接就启动线程去处理? 
    http://blog.csdn.net/xianfajushi/article/details/7609849