2012-12-26 89 views
4

關閉表單我有一個使用ShowDialog的功能推出了一個表單管理器類。現在,我開始一個事件(如定時器),並希望管理者在定時器到期以關閉表單。從另一個線程

我用了2類:

namespace ConsoleApplication3 
{ 
class Manager 
{ 
    Timer UpdTimer = null; 
    readonly int REFRESH_STATUS_TIME_INTERVAL = 5000; 
    Form1 form1; 

    public Manager() 
    { 
    } 

    public void ManageTheForms() 
    { 
     UpdTimer = new Timer(REFRESH_STATUS_TIME_INTERVAL); 
     // start updating timer 
     //UpdTimer.Interval = REFRESH_STATUS_TIME_INTERVAL; 
     UpdTimer.Elapsed += new ElapsedEventHandler(PriorityUpdTimer_Elapsed); 
     UpdTimer.Start(); 

     form1 = new Form1(); 
     form1.ShowDialog(); 


    } 

    public void PriorityUpdTimer_Elapsed(object source, ElapsedEventArgs e) 
    { 
     UpdTimer = null; 
     form1.closeFormFromAnotherThread(); 

    } 
} 
} 

Form1類:

namespace ConsoleApplication3 
{ 
public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
    { 

    } 


    delegate void CloseFormFromAnotherThread(); 

    public void closeFormFromAnotherThread() 
    { 
     if (this.InvokeRequired) 
     { 
      CloseFormFromAnotherThread del = new CloseFormFromAnotherThread(closeFormFromAnotherThread); 
      this.Invoke(del, new object[] { }); 
     } 
     else 
     { 
      this.Close(); 
     } 
    } 

} 

}

+2

哪裏是你的問題就在這裏?你的代碼是否會拋出任何錯誤? – ryadavilli

+0

作爲一個側面節點,我確實發現了內存泄漏。 UdpTimer將通過事件訂閱保持活動狀態,即使在計時器過去之後。你應該明確地unsubscribe-或使用lambda /匿名方法中調用close方法的用戶。 – Polity

回答

1

如果我是正確的,你要關閉的形式計時器停止時。

這是我做的方式:

System.Threading.Timer formTimer; 

我用一個布爾值,看看是否計時器仍然活躍

public Boolean active { get; set; } 

創建此功能:

public void timerControl() 
{ 
    if (!active) formTimer = new System.Threading.Timer(new TimerCallback(TimerProc)); 
    try 
    { 
    formTimer.Change(REFRESH_STATUS_TIME_INTERVAL, 0); 
    } 
    catch {} 
    active = true; 
} 

要完成你所需要的功能的TimerProc,這就是所謂的計時器時,有創造了一個新的計時器:

private void TimerProc(object state) 
{ 
    System.Threading.Timer t = (System.Threading.Timer)state; 
    t.Dispose(); 
    try 
    { 
    CloseScreen(); 
    } 
    catch{} 
} 

爲了讓我更容易編程我做了功能CloseScreen():

public void CloseScreen() 
{ 
    if (InvokeRequired) 
    { 
    this.Invoke(new Action(CloseScreen), new object[] { }); 
    return; 
    } 
    active = false; 
    Close(); 
} 

把所有這些功能在你的窗體類,只需使用timerControl到ACTIVAT計時器。您可以選擇從Manager類訪問:Form1.TimerControl();或者把它放在一個事件處理程序,更迭!