Basically I have a form with a button, when the button is pressed it creates an instance of a class that runs a Thread. When the thread is done, it automatically calls Thread.Abort().
The code I currently have comes down to this:
Button:
private void Buttonclick(object sender, EventArgs e)
{
MyClass c = new MyClass()
c.Do_your_thing();
}
Class:
public class MyClass
{
Thread t;
public void Do_your_thing()
{
t = new Thread(Running_code);
t.Start();
}
private void Running_code()
{
//Perform code here
t.Abort();
}
}
When I click the button once, everything works. But when I press the button again, nothing happens.
When I don't use t.Abort() everything works. But not using t.Abort() will cause memory leaks and the program won't close properly (the thread is never closed, therefor the process will stay alive).
Can anyone explain me what is going on? And how can I fix it?
EDIT: as per request I am posting some actual code
public class MyClass
{
public void Test()
{
t = new Thread(() =>
{
wb.DocumentCompleted += get_part;
wb.Navigate("http://www.google.com");
Application.Run();
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
public void get_part(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var br = sender as WebBrowser;
string url = e.Url.ToString();
//Here is some code that compares the url to surten predefined url. When there is a match, it should run some code and then go to a new url
if(url == string_final_url)
{
//Finally at the url I want, open it in a new Internet Explorer Window
Process proc = Process.Start("IExplore.exe", url);
}
}
}
This is a fraction of a little webscraper program. It navigates to a webpage that needs some login info. When I reached the page I actually want to be, he should open it in a new Internet Explorer.
When I call this code and close the form, it's still visible in the process tree. And when I click the button multiple times, the memory used keeps getting higher, which I suspected to be some sort of memory leak.