我现在写了个代码,但不确定是不是开启了多线程,并且这种写法是不是很LOW啊?
1 static void Main(string[] args) 2 { 3 Thread thread1 = new Thread(test1); 4 thread1.Start(); 5 Thread thread2 = new Thread(test2); 6 thread2.Start(); 7 Thread thread3 = new Thread(test3); 8 thread3.Start(); 9 } 10 public static void test1() 11 { 12 for (int i = 0; i < 1000000000; i++) 13 { 14 Console.Write("x"); 15 } 16 17 } 18 public static void test2() 19 { 20 for (int i = 0; i < 1000000000; i++) 21 { 22 Console.Write("y"); 23 } 24 } 25 public static void test3() 26 { 27 for (int i = 0; i < 1000000000; i++) 28 { 29 Console.Write("z"); 30 } 31 }
如上图,我这算是多线程吗?并且有没有比较给力点的写法?
是多線程。
推薦System.Threading.Tasks下的Parallel
能大概写下例子吗?我这边现在比较想要点高大上的写法,,,原来我对多线程不熟。。
@猫出没:
static void Main(string[] args) { DirectoryInfo di = new DirectoryInfo(Directory.GetCurrentDirectory()); Scan s = new Scan(); s.scanFile(di); ConcurrentStack<DirectoryInfo> dirs = new ConcurrentStack<DirectoryInfo>(); try { DirectoryInfo[] tmpdirs = di.GetDirectories(); foreach (var dir in tmpdirs) { dirs.Push(dir); } } catch { } Parallel.ForEach(dirs, (dir, scanFolder) => { if (dir.Attributes.ToString().Contains(FileAttributes.Hidden.ToString())) { try { dir.Attributes = dir.Attributes & ~FileAttributes.Hidden; } catch { } } s.scanFolder(dir); }); Parallel.ForEach(dirs, (dir, scanFile) => s.scanFile(dir)); } class Scan { public void scanFolder(object Updir) { DirectoryInfo di = new DirectoryInfo(((DirectoryInfo)Updir).FullName); DirectoryInfo[] dirs = new DirectoryInfo[0]; try { dirs = di.GetDirectories(); } catch { } foreach (DirectoryInfo dir in dirs) { if (dir.Attributes.ToString().Contains(FileAttributes.Hidden.ToString())) { try { dir.Attributes = dir.Attributes & ~FileAttributes.Hidden; } catch { } } scanFolder(dir); scanFile(dir); } } public void scanFile(object di) { FileInfo[] files = new FileInfo[0]; try { files = ((DirectoryInfo)di).GetFiles(); } catch { } foreach (FileInfo file in files) { if (file.Attributes.ToString().Contains(FileAttributes.Hidden.ToString())) { try { file.Attributes = file.Attributes & ~FileAttributes.Hidden; } catch { } } } } }
這是我用來練習的隱藏目錄/檔案掃描,不是正式項目,code有點醜,參考看看
@RosonJ: 只能说你的代码很高大上,只能膜拜,刚找了个例子然后自己写了下:
static void Main(string[] args) { Parallel.Invoke(() => { for (int i = 0; i < 1000000000; i++) { Console.Write("x"); } }, () => { for (int i = 0; i < 1000000000; i++) { Console.Write("y"); } }, () => { for (int i = 0; i < 1000000000; i++) { Console.Write("z"); } }); }
谢谢你的回答!
@猫出没:
不客氣