I have some links in my program which I must open the links in Web Browser one by one and enter some data in Web page.
The links list is provided in GUI Thread. But I need to do some works with links outside of Main Thread to avoid of Lagging and Hanging the GUI. And I need to open links one after the other. I mean if a thread starts to working, the next thread will start only when the thread finish works.
Another important thing about Links list is that when threads are created and working, Links List is updating.
So I created a worker thread which manages starting of another Threads.
I have two AutoResetEvents
, one for checking the list that is empty or not (postInQueue
). If the list is empty, it's wait until a link will added to list and calls postInQueue.set()
.
The second one is threadInProgress that when a thread is started working, it's waiting until the thread calls threadInProgress.set()
;
AutoResetEvent threadInProgress = new AutoResetEvent(False);
AutoResetEvent postInQueue = new AutoResetEvent (False);
List<String> links = new List<String>;
public MainForm(){
InitializeComponent();
Thread threadManager = new Thread( () =>
{
while(true){
if (postsQueue.Count == 0)
postInQueue.WaitOne();
Thread t2 = new Thread(() => {
linkProcess(links[0]);
};
t2.SetApartmentState(ApartmentState.STA);
t2.Start();
threadInProgress.WaitOne(60000);
links.RemoveAt(0);
}
});
threadManager.start();
}
public void linkProcess(String link){
WebBrowser webBrowser = new WebBrowser();
webBrowser.DocumentCompleted += (s , e) => {
//Enter some data in webBrowser
Application.ExitThread();
threadInProgress.set();
};
webBrowser.Navigate(link);
Application.Run();
}
I Must call Application.Run()
in each thread to DocumentCompleted
Event will be called.
This code works well for two or three first links but next threads will be stuck in Application.Run()
until threadInProgress.WaitOne(60000);
send timeout.
Two first links works correct but then I realized that CPU usage is 0%. When I click on break all, I see that the thread is stucking in Application.Run()
.
What is the problem?
In a forum, someone advise me to use process except thread... How can this be possible? And would be helpful?