我想寻求你的帮助,在我的C#程序中实现多线程。
该计划旨在将10,000 ++文件上传到ftp服务器。我计划至少实现10个线程以提高进程的速度。
有了这个,这就是我的代码行:
我初始化了10个主题:
public ThreadStart[] threadstart = new ThreadStart[10];
public Thread[] thread = new Thread[10];
我的计划是将一个文件分配给一个线程,如下所示:
file 1 > thread 1
file 2 > thread 2
file 3 > thread 3
.
.
.
file 10 > thread 10
file 11 > thread 1
.
.
.
所以我有以下内容:
foreach (string file in files)
{
loop++;
threadstart[loop] = new ThreadStart(() => ftp.uploadToFTP(uploadPath + @"/" + Path.GetFileName(file), file));
thread[loop] = new Thread(threadstart[loop]);
thread[loop].Start();
if (loop == 9)
{
loop = 0;
}
}
将文件传递到各自的线程正在运行。我的问题是线程的启动是重叠的。
异常的一个例子是当线程1运行时,会传递一个文件。它返回一个错误,因为线程1尚未成功完成,然后一个新参数被传递给它。其他线程也是如此。
实施此方法的最佳方法是什么?
任何反馈都将不胜感激。谢谢! :)
答案 0 :(得分:1)
使用async-await并将一组文件传递给它:
private static async void TestFtpAsync(string userName, string password, string ftpBaseUri,
IEnumerable<string> fileNames)
{
var tasks = new List<Task<byte[]>>();
foreach (var fileInfo in fileNames.Select(fileName => new FileInfo(fileName)))
{
using (var webClient = new WebClient())
{
webClient.Credentials = new NetworkCredential(userName, password);
tasks.Add(webClient.UploadFileTaskAsync(ftpBaseUri + fileInfo.Name, fileInfo.FullName));
}
}
Console.WriteLine("Uploading...");
foreach (var task in tasks)
{
try
{
await task;
Console.WriteLine("Success");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
然后这样称呼:
const string userName = "username";
const string password = "password";
const string ftpBaseUri = "ftp://192.168.1.1/";
var fileNames = new[] { @"d:\file0.txt", @"d:\file1.txt", @"d:\file2.txt" };
TestFtpAsync(userName, password, ftpBaseUri, fileNames);
答案 1 :(得分:0)
为什么要这么做呢? .net已经有一个名为ThreadPool的类。 您可以使用它并管理线程本身。 你的代码将是这样的:
static void DoSomething(object n)
{
Console.WriteLine(n);
Thread.Sleep(10);
}
static void Main(string[] args)
{
ThreadPool.SetMaxThreads(20, 10);
for (int x = 0; x < 30; x++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomething), x);
}
Console.Read();
}