c#线程很简单的,给点代码,你再查查msdn扩展下吧,就是要注意多线程同步问题//利用线程池执行
System.Threading.ThreadPool.QueueUserWorkItem(new WaitCallback(method));//委托给的方法
private static void method(object obj)
{
StringBuilder strOutKey = new StringBuilder();
string[] aryTempKey = content.Replace("\r\n", "$").ToString().Split( '$ '); Hashtable hNew = new Hashtable();
int m = 0, all = 0, s = 0; foreach (string strKey in aryTempKey)
{
if (!hNew.ContainsValue(strKey))
{
hNew.Add(s, strKey);
strOutKey.Append(strKey + "\r\n");
}
else
m++; s++;
}
all = hNew.Count;
}
System.Threading.ThreadPool.QueueUserWorkItem(new WaitCallback(method));//委托给的方法
private static void method(object obj)
{
StringBuilder strOutKey = new StringBuilder();
string[] aryTempKey = content.Replace("\r\n", "$").ToString().Split( '$ '); Hashtable hNew = new Hashtable();
int m = 0, all = 0, s = 0; foreach (string strKey in aryTempKey)
{
if (!hNew.ContainsValue(strKey))
{
hNew.Add(s, strKey);
strOutKey.Append(strKey + "\r\n");
}
else
m++; s++;
}
all = hNew.Count;
}
注意,线程池中的线程是后台线程,也就是说,主线程结束,后台线程也随之停止。
但是如果是用专用线程,也就是new Thread(),然后Start(),则不一样,只有当专用线程也结束,主线程才停止。
所以要看具体情况来使用了
strOutKey.Append(strKey + "\r\n");
是不是单独写成方法,2个线成同时运行?
因为strOutKey是依赖hNew的
是否让他延时几秒,等hNew有直了,再去调用strOutKey吗?
谢谢上面2位,还是不很清楚
private static void method(object obj)
{
StringBuilder strOutKey = new StringBuilder(500000);
//如果数据很大,建议StringBuilder(500000)这里设大一点,它的初始值较小
string[] aryTempKey = content.Replace("\r\n", "$").ToString().Split( '$ '); Hashtable hNew = new Hashtable();
int m = 0, all = 0, s = 0; foreach (string strKey in aryTempKey)
{
if (!hNew.ContainsValue(strKey))
{
hNew.Add(s, strKey);
strOutKey.Append(strKey + "\r\n");
}
}
s=all=hNew.Count;
m=strOutKey.Length - hNew.Count();
}
有点小问题,请改为
m=strOutKey.Length - hNew.Count;
改为:
string[] aryTempKey = Regex.Split(content,@"\r\n ",RegexOptions.Multiline);
string[] aryTempKey = content.Replace("\r\n", "$").ToString().Split( '$ ');
这步很快,主要还是在循环里面能再优化吗,比如说用正则表达式
还有加字符这步是最慢的,能有其他方法吗
多cpu 执行 多线程对于 大数据的读取 实际没什么提高
这里关键的 内存和 i/o处理的能力