天天看點

winfrom中Application.Restart()

System.Windows.Forms.Application.Restart();方法系統實作自動重新開機。

            if (FrmDialog.ShowDialog(this, "确定登出嗎?", "提示", false, false, false, null, DialogType.YesNo) == DialogResult.OK)
            {
                System.Windows.Forms.Application.Restart();
            }      

花了接近一天的時間,才研究出來這個系統自動重新開機時好時壞的問題。  

應用.net自帶的Application.Restart();有時候重新啟動好用,而有時就是起不來,特别啟動次數多了和電腦比較老舊時老出現。查找了好多相關的資料,都沒能嘗試成功。

但是不管怎樣我覺得這個說的還算是對我有用粘貼過來。

  If Application.Restart is called from any thread in a normally run Windows Forms application, the application shuts down and restarts. 
In a ClickOnce deployed application, this can be used to cause the application to restart after an update has been downloaded using the ApplicationDeployment class. 
However, if you call Application.Restart from a non-UI thread (i.e a thread pool thread in the BackgroundWorker.DoWork event), the application is shut down but not restarted.       

感覺網上很不贊成應用Application.Restart();方法的,因為,可能導緻它不好用的原因很多,會很莫名其妙,但是系統确實就有這樣的需求,是以,隻能不得已而為之。

這次解決的辦法,我總結主要是這個原因,在系統要求自動重新開機的時候,首先要關閉原有的所有程序,但是重新開機的這個方法,會因為在沒有完全關閉的時候就啟動,這樣方法本身沖突發生異常就會被關閉,是以,重新啟動失敗。最後,将Program中的啟動線程挂起1秒,問題便解決了。

//解決Restart方法沖突問題
            System.Threading.Thread.Sleep(1000);