Click here to Skip to main content
15,890,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello

Application.Restart(); not work in Task method
Closed Application but not run again Automaticly

What I have tried:

I Have this Code Block 

<pre lang="c#">Task.Delay(ts).ContinueWith((x) =>
                {
                    bool updateSuccess = checkUpdate2();
                    if (updateSuccess)
                    {
                        restart();
                    }
                    else
                    {
                        notifyIcon1.ShowBalloonTip(3000, "UPDATE", "No current updates found", ToolTipIcon.Info);
                        Thread.Sleep(3000);
                    }
                });


C#
public void restart()
        {
            try
            {
                this.scannerService.Stop();
                this.travelDocumentScannerService.Stop();
                this.printerService.Stop();
                MessageBox.Show("Servisler Stopped");

                this.mouseThread.Abort();
                MessageBox.Show("Thread closed");

                Thread.Sleep(3000);

                Application.Restart();
            }
            catch (Exception ex)
            {
                var f = ApplicationDeployment.CurrentDeployment.DataDirectory +@"\RestartError.txt";
                var err = "Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
   "" + Environment.NewLine + "Date :" + DateTime.Now.ToString();
                if (!File.Exists(f))
                {
                    File.WriteAllText(f, err);
                }
                else
                {
                    File.AppendAllText(f, err);
                }
            }
        }



Everything run good but after call
Application.Restart();
Application closed and not run autotmaticly and dont give Exception too

if I run restart() method manual code work fine and restart Application but when it run in Task it doesnot work

where am I making a mistake
Posted
Updated 22-Jul-19 1:21am

1 solution

As far as I'm aware, you can't do Application.Restart except on the main thread - because part of the Restart operation involves closing the forms and that will terminate any sub-threads that the app has opened. When the thread closes, the sub-thread terminates, and it doesn't get to the code that starts the new instance to replace it.

Three solutions:
1) Call Restart from the main thread instead of sub-thread.
2) Try Process.Start(Application.ExecutablePath), wait a moment, then close the app.
3) Find a more graceful way to unwind your application - restarting is almost certainly a kludge!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900