循环100次调用启动线程方法,启动100线程,每个线程往硬盘写文件,文件名可以是当前时间+线程号+随机数,这样利于你看结果
已经写了一个,但是感觉不太好啊,指点一下
1 class Program 2 { 3 static string txt; 4 static void Main(string[] args) 5 { 6 txt = GetRandomString(104857600); 7 8 //Console.WriteLine("Begin in Main"); 9 10 ThreadPool.SetMaxThreads(100, 100); 11 ThreadPool.SetMinThreads(100, 100); 12 while (true) 13 { 14 ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadInvoke)); 15 Thread.Sleep(500); 16 } 17 18 19 } 20 21 static void ThreadInvoke(Object param) 22 { 23 var path = "E:\\Test\\" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_ms") + newId()+ ".txt"; 24 Console.WriteLine("正在写入文件:"+path); 25 FileStream fs = new FileStream(path, FileMode.CreateNew); 26 StreamWriter sw = new StreamWriter(fs); 27 28 sw.Write(txt); //这里是写入的内容 29 sw.Flush(); 30 Console.WriteLine("写入成功"); 31 //Console.WriteLine("Execute in ThreadInvoke"); 32 //每隔100毫秒,循环一次 33 //Thread.Sleep(100); 34 } 35 36 /// <summary> 37 /// 全局唯一标识符 38 /// </summary> 39 public static string newId() 40 { 41 return Guid.NewGuid().ToString("N"); 42 } 43 44 /// <summary> 45 /// 生成指定长度字符串 46 /// </summary> 47 /// <param name="length"></param> 48 /// <returns></returns> 49 private static string GetRandomString(int length) 50 { 51 const string key = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; 52 if (length < 1) 53 return string.Empty; 54 55 Random rnd = new Random(); 56 byte[] buffer = new byte[8]; 57 58 ulong bit = 31; 59 ulong result = 0; 60 int index = 0; 61 StringBuilder sb = new StringBuilder((length / 5 + 1) * 5); 62 63 while (sb.Length < length) 64 { 65 rnd.NextBytes(buffer); 66 67 buffer[5] = buffer[6] = buffer[7] = 0x00; 68 result = BitConverter.ToUInt64(buffer, 0); 69 70 while (result > 0 && sb.Length < length) 71 { 72 index = (int)(bit & result); 73 sb.Append(key[index]); 74 result = result >> 5; 75 } 76 } 77 return sb.ToString(); 78 } 79 80 81 }
这种用线程池来管理线程,会额外增加线程轮换的开销,而且你ThreadPool.SetMaxThreads(100, 100) 设置最大线程数,那么就没有100线程在写文件。但用于测试也是可以的。
@ndgail: 线程大神给个demo可好
@Alone章鱼: 我随便贴点你自己补充吧,
1. for循环调用开启线程方法
static void Start()
{
Thread process_Thread = new Thread(PorcessItem);
process_Thread.IsBackground = true;
process_Thread.Start();
}
static void PorcessItem(){
//循环写文件到硬盘
}
未经测试,你自己试下