开发者

How to Managed ALL running Threads in C# console appication?

开发者 https://www.devze.com 2023-03-01 04:38 出处:网络
I having problem managed thread paralle开发者_开发技巧l in console application. I am running 10 threads parallel & all thread doing some specific task.

I having problem managed thread paralle开发者_开发技巧l in console application.

I am running 10 threads parallel & all thread doing some specific task.

In case if any task is over/completed then doing stop/end thread and immediate I started new thread instance.

I want 10 threads so anyone thread is going to stop/end then It generates new thread.

but every time I want 10 threads in running mode in console application &

It should be parallel work using C# console application.

How I can running 10 threads in C# console application?


At the end of each thread put a lock on some shared object (lock (obj) {}). Then remove the current thread from a collection of threads you have. If the collection.Count is less than 10 create a new one and put inside the collection. Release the lock.

private List<Thread> threads = new List<Thread>();

private void ThreadFunction() {
  // do something
  // here before the lock
  lock (threads) {
    threads.Remove(Thread.CurrentThread);
    if (thread.Count < 10) {
      Thread t = new Thread(ThreadFunction);
      threads.Add(t);
      t.Start();
    }
  }
}

Be sure to catch all exception inside the thread or you code will fail when a thread exception happens. That is make sure that the lock part of the code is always called (except on a Thread abord exception but that will not matter).

But as stated I think you should use a ThreadPool for such a task...


The book on threads in .Net is: http://www.albahari.com/threading/ This alone will probably answer any questions you have.

Depending on what you are using these threads for (I am guessing that you may be talking about running transactions in the background) you may want to use BackgroundWorker.

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

BackgroundWorker lets you deal with Begin/End/Progress Events only, making debugging much less error prone.

0

精彩评论

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

关注公众号