开发者

c# windows form does not respond while multithreading

I have a windows form with just two functionalities : the first one is loading some rows in a database and the second functionality is processing those rows using a given number of 开发者_Go百科threads because processing speed is very important in my project that's why i can not consider the option of not using multithreading.

The problems relies that i want to add the option of stopping execution of the process, meaning stopping all of current threads if any problem occurs, so that the user specify another nr of threads and restart execution again, but my windows form seems freezing and execution enters stopping method after all threads have normally finished their work.

In more detail in processing button click event I am initiating all threads and after that I am looping all threads

for (int i = 0; i < threads.Length; i++)
{
      threads[i].Join();
}

while in button click event for stop I

for(int i=0;i<threads.Length;i++)
{
     if(threads[i].IsAlive)
     threads[i].Abort();
}

i noticed that if i comment the joining part the interface is able to respond to stop event clicking.

But i don't want to do that because I want to distinguish the moment when all the threads have finished executing thats why i put joining pa


I assume you do the join-loop on the main thread. That means the message-loop is halted until the last thread finishes, defeating the multi-threading. And it blocks the processing of all events, including button-clicks.

Aside, you shouldn't use Thread.Abort()

You will have to think of a better plan

  • the thread-code should check for a stop flag
  • If you absolutely need that join-patten, do it from another thread. Maybe from a backgroundworker.


Calling Join forces your main thread to wait for all other threads and counteracts your multithreading, exactly what you don't want. Calling Abort abandons the thread and prevents you from getting any results from it. Don't do that.

It's possible to set up a thread with callbacks to return results, and poll to see if the thread should be canceled, but the easiest thing is to use BackgroundWorker, a .Net class designed specifically to do what you are trying to do. There is a good tutorial at Code Project.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜