取消線程Timer我試圖實現在自己的代碼Thread.Timers MSDN的例子(http://msdn.microsoft.com/en-us/library/swx5easy.aspx)。從另一個類
我希望能夠取消定時器執行某個用戶操作時,但我不能處理定時器,我懷疑這是因爲我調用另一個類的方法,所以我需要調整;但我不知道在哪裏。
除此之外,定時器工作正常。任何人都可以看到爲什麼我的計時器不會取消時,調用btnconfigOpenConfig?
僅供參考,我將什麼工作進程定時事件。
public partial class Xservt : Window
{
internal class TimerStateObjClass
{
public int SomeValue;
public System.Threading.Timer SqlUpdateFromTwitterTimerReference;
public bool TimerCanceled;
}
internal void SomeMethod(){
TimerStateObjClass stateObj = new TimerStateObjClass();
stateObj.TimerCanceled = false;
stateObj.SomeValue = 100;
System.Threading.TimerCallback timerDelegate =
new System.Threading.TimerCallback(twit.hometimelineclass._sqlUpdateFromTwitterWorker_DoWork);
var sqlUpdateFromTwitterTimer = new Timer(timerDelegate, stateObj, 0,20000);
stateObj.SqlUpdateFromTwitterTimerReference = sqlUpdateFromTwitterTimer;
}
}
//action to perform which disposes the timer
private void btnconfigOpenConfig(object sender, RoutedEventArgs e)
{
TimerStateObjClass timerState = new TimerStateObjClass();
timerState.TimerCanceled = true;
}
//Actions the timer is calling, in another class
internal static void _sqlUpdateFromTwitterWorker_DoWork(object StateObj)
{
Xservt.TimerStateObjClass state = (Xservt.TimerStateObjClass) StateObj;
if(state.TimerCanceled)
{
state.SqlUpdateFromTwitterTimerReference.Dispose();
}
//some work
}
您正在創建TimerStateObjClass的*新*的對象。這不能工作,而是向你的班級添加一個私人領域。 – 2012-04-28 13:17:01
到TimerStateObjClass?類型TimerStateObjClass的 – Damo 2012-04-28 13:23:13
,是。 – 2012-04-28 13:32:38