日期:2014-05-17  浏览次数:20327 次

.net 多线程中有的线程没有结果
[code=C#][/code]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.Remoting.Messaging;
using ConsoleApplication1;
using System.Collections;
  public static void Main()
  {
  new delegateClass().test();
  }
  /// <summary>
  /// 第一轮委托
  /// </summary>
  public delegate void FirstDelegate(object o);

  /// <summary>
  /// 第一轮委托调用结束后处理
  /// </summary>
  /// <param name="ar"></param>
  public void DelFirstDelegate(IAsyncResult ar)
  {
  if (count > 0)
  --count;
  AsyncResult asyncResult = ar as AsyncResult;
  FirstDelegate fd = asyncResult.AsyncDelegate as FirstDelegate;
  fd.EndInvoke(ar);
  }
  public void test()
  {
  int threadCount = 100;
  Console.WriteLine("顺序输出100个1");
  for (int i = 0; i < threadCount; i++)
  {
  Console.Write("1");
  }
  Console.WriteLine("\r\n线程输出100个1");
  for (int j = 0; j < 5; j++)
  {
  for (int i = 0; i < threadCount; i++)
  {
  while (count > 50)
  {
  CheckThreadPool(0);
  }
  ++count;
  ThreadPool.QueueUserWorkItem(new WaitCallback(exec), new List<string> { { "1" } });
  }
  while (!CheckThreadPool()) { };
  Console.WriteLine(str);
  str = "";
  }
  }
  //检查线程池的方法
  private bool CheckThreadPool(int diff = 0)
  {
  int workerThreads = 0;
  int maxWordThreads = 0;
  //int 
  int compleThreads = 0;
  ThreadPool.GetAvailableThreads(out workerThreads, out compleThreads);
  ThreadPool.GetMaxThreads(out maxWordThreads, out compleThreads);
  //当可用的线数与线程池最大的线程相等时表示线程池中所有的线程已经完成
  if (workerThreads + diff == maxWordThreads)
  {
  return true;
  }
  return false;
  }
  int count = 0;
  string str = "";
  public void exec(object o)
  {
  List<string> lst = o as List<string>;
  foreach (string str in lst)
  {
  FirstDelegate fir = new FirstDelegate(print);
  fir.BeginInvoke(str, new AsyncCallback(DelFirstDelegate), null);
  }
  }
  public void print(object o)
  {
  str += "1";
  }

  }
为什么多线程输出的时候长度不等于顺序输出的结果呢,是不是有的线程进入了无限的等待中,还是有的线程根本就没在程序池里面。该如何保证所有的线程都运行呢?

------解决方案--------------------
参数多线程 共享冲突
------解决方案--------------------
并发了~~~