2012-11-23 58 views
1

首先,我不知道這是否是一個愚蠢的問題。我有這樣的情況,首先我有一個主窗口關閉後窗口仍然調用方法

public MainWindow() 
{ 

    InitializeComponent(); 
    //dt is a System.Windows.Threading.DispatcherTimer variable 
    dt = new System.Windows.Threading.DispatcherTimer(); 
    dt.Interval = new TimeSpan(0, 0, 0, 0, 30000); 
    dt.Tick += new EventHandler(refreshData); 

    dt.Start(); 

} 

的refreshData方法做到這一點:

public void refreshData(object sender, EventArgs e) 
{ 
    Conection c = new Conection(); 
      //this method just returns 'hello' doesn't affect my problem 
    c.sayHello(); 
} 

這個主窗口也有一個按鈕,當我點擊該按鈕,我打電話給另一個類

private void button1_Click(object sender, RoutedEventArgs e) 
{ 
    ShowData d = new ShowData(); 
    d.Show(); 
} 

這個類是非常相似的主窗口,它有自己的DispatcherTimer太

public ShowData() 
{ 
    InitializeComponent(); 

    dt = new System.Windows.Threading.DispatcherTimer(); 
    dt.Interval = new TimeSpan(0, 0, 0, 0, 30000); 
    dt.Tick += new EventHandler(refreshData); 

    dt.Start(); 
} 

public void refreshData(object sender, EventArgs e) 
{ 
    Conection c = new Conection(); 
    c.sayHello(); 
} 

我跟蹤調用與Visual Studio調試器的SayHello,問題是當我關閉「ShowData」窗口中,從ShowData類的sayHello呼叫仍然出現在

難道我沒有正確關閉窗口?關閉窗口後如何停止呼叫?

PS:我嘗試設置DispatcherTimer爲NULL on_closing事件

+0

你試過阻止它嗎? http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchertimer.stop.aspx –

+0

@AustinSalonen我不知道!我已經嘗試過並努力工作,我知道這是一件愚蠢的事情......謝謝! –

+0

@NatyBizz請查看我的答案。 – dknaack

回答

1

您需要使用Stop()方法你的窗口OnWindowClosing事件停止DispatcherTimer。

public class MainWindow : Window 
{ 
    DispatcherTimer MyTimer; 

    public MainWindow() 
    { 
     InitializeComponent(); 

     MyTimer = new System.Windows.Threading.DispatcherTimer(); 
     MyTimer.Interval = new TimeSpan(0, 0, 0, 0, 30000); 
     MyTimer.Tick += new EventHandler(refreshData); 
     // Start the timer 
     MyTimer.Start(); 
    } 

    public void OnWindowClosing(object sender, CancelEventArgs e) 
    { 
     // stop the timer 
     MyTimer.Stop(); 
    } 

    public void refreshData(object sender, EventArgs e) 
    { 
     Conection c = new Conection(); 
     c.sayHello(); 
    } 
} 
+0

謝謝,雖然很奇怪,對我來說,一扇窗戶在被關閉後完全被破壞了 –

+0

是的,但派遣者是一個新線程。而不是窗戶所在的UI線程 – dknaack

相關問題