从另一个线程启动/停止DispatcherTimer

Gow*_*ham 7 c# silverlight silverlight-4.0 windows-phone-7 windows-phone-7.1

这是我的代码..

public DispatcherTimer tmr = new DispatcherTimer();

void somefunction (parameters){

if (something)
  tmr.Start();
if (something else)
  tmr.Stop();

   }
Run Code Online (Sandbox Code Playgroud)

我的问题是我无法从第二个函数访问tmr对象的Start/Stop方法,因为它在不同的线程上运行!

有人能帮帮我吗??我被这个问题打了将近3天!:(

Muh*_*han 2

您需要通过 Dispatcher 调用它(用于整理来自另一个线程的调用),如下所示

Deployment.Current.Dispatcher.BeginInvoke((Action)(()=>timer.Start())
Run Code Online (Sandbox Code Playgroud)

  • +1 然而,实际上不需要将 () 的 lambda 转换为 `Action`,因为计时器.Start 具有与 `Action` 相同的签名,根本不需要 lambda。这将起作用:`Deployment.Current.Dispatcher.BeginInvoke(timer.Start);` (2认同)