日期:2014-05-19  浏览次数:20879 次

关于多线程处理的问题,请大家帮忙看一下,急!!谢谢
我想将某个目录下的所有文件做一个转换操作,单线程的操作部分代码如下:
while(true)
{
files=System.IO.Directory.GetFileSystemEntries(@ " "+sourcepath);

foreach(string       path       in       files)          
{      
if(File.Exists(path))          
{      
//////处理文件开始       改成用两个线程来同时处理,应该怎么做?????
convertVideo(path);
//////处理文件结束


}                                                                  
}        


Thread.Sleep(1);

}//while


public   static   void   convertVideo(string   path)  
{
//这部分代码已写好了
}

现在我想把处理文件那部分改成多线程的,同时处理两个文件,不知道这部分代码怎么改?请大家帮我一下,谢谢!

------解决方案--------------------
全部的.我这里可以通过编译
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading;

class Programe
{
static void Main()
{
string sourcepath = " ";
while (true)
{
string[] files = System.IO.Directory.GetFileSystemEntries(@ " " + sourcepath);
List <string> fileList = new List <string> (files);
Thread th1 = new Thread(WorkRoutine);
Thread th2 = new Thread(WorkRoutine);
th1.Start(fileList);
th2.Start(fileList);
th1.Join();
th2.Join();
}
}

private static void WorkRoutine(object obj)
{
List <string> li = (List <string> )obj;
string path = null;
while (true)
{
lock (li)
{
if (li.Count == 0)
{
return;
}
path = li[0];
li.RemoveAt(0);
}
//convertVideo(path);
}
}
}