在线程中动态定义事件

时间:2013-12-14 19:31:55

标签: c# wpf

我创建了一个线程并在其上创建了一个DispatcherTimer。在这个线程中,我为Tick事件定义了一个方法,但它永远不会发生。

class Net
{
    List<DispatcherTimer> Timers;
    Thread thread;

    Net()
    {
        thread = new Thread(method);
        Timers=new List<DispatcherTimer>();
        thread.Start();
    }

    void method()
    {
        while(true)
            if(condition)
            {
                Timers.Add(new DispatcherTimer());
                Timers[Timers.Count - 1] = new DispatcherTimer();
                Timers[Timers.Count - 1].Interval = new TimeSpan(2000000);
                Timers[Timers.Count - 1].Tick += new EventHandler(Timers_Tick);
                Timers[Timers.Count - 1].IsEnabled = true;
                Timers[Timers.Count - 1].Start();
            }
    }
    private void Timers_Tick(object sender, EventArgs e)
    {
        //Some Code
    }
}

编辑:在原始代码中是的,我启动了线程。

1 个答案:

答案 0 :(得分:0)

DispatcherTimer应该是run on UI thread,但是您尝试从后台线程创建它,其Dispatcher与UI调度程序不同。

因此,您应该将UI调度程序传递给该方法,并将该调度程序用于dispatcherTimer对象 -

thread = new Thread(() => method(App.Current.Dispatcher));

void method(Dispatcher dispatcher)
{
   ....
   Timers.Add(new DispatcherTimer(DispatcherPriority.Background, dispatcher));
   Timers[Timers.Count - 1] = new DispatcherTimer(DispatcherPriority.Background,
                                                  dispatcher);
   ...
}

或者您应该使用Timer代替DispatcherTimer