Is there any way i can create a thread which ends no matter what after 1 min?
Currently i make a thread to login to a website code is below:
private void runBrowserThread()
{
specialCheck = 0;
var th = new Thread(() =>
{
var br = new WebBrowser();
browserCounter = 0;
br.ScriptErrorsSuppressed = true;
br.DocumentCompleted += browser_DocumentCompleted;
br.Navigate("https://www.xample.com/login");
Application.Run();
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
th.Join();
}
BUT there are a lot of complications in the process so i do not want to code them all , what i am thinking something like a self destruct i can use when making this timer ,so that no matter what if a code is stuck , it does not reach one of the Application.Exitthread() it will be stuck there forever so a self destruct after 1 min , Exits the threads so the code can move on.
Because currently i have Application.Exitthread() at many places but i sometimes the code is stuck does not reach any, so let me know if there is any way.
As you’re already blocking on
th.Joinyou could use that to terminate the thread, like so:If you don’t want to block on Join, then you could spawn a second watchdog thread that exists only to block on
Joinand perform the timeout and termination task instead of the instigator thread.Also, use of
Application.ExitThreadisn’t good design. Threads can terminate byreturning from their entrypoint method – it also removes an unnecessary dependence on theApplicationclass and its associatedSystem.Windows.Formsassembly.