gpt4 book ai didi

c# - 多线程并加快处理速度

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:56 25 4
gpt4 key购买 nike

我有以下代码。我希望在多个线程上开始文件创建。目的是在多个线程上创建10个文件时将花费更少的时间。据我了解,我需要引入异步调用的元素来实现这一目标。

我应该在这段代码中进行哪些更改?

using System;
using System.Text;
using System.Threading;
using System.IO;
using System.Diagnostics;

namespace MultiDemo
{
class MultiDemo
{
public static void Main()
{
var stopWatch = new Stopwatch();
stopWatch.Start();
// Create an instance of the test class.
var ad = new MultiDemo();

//Should create 10 files in a loop.
for (var x = 0; x < 10; x++)
{
var y = x;
int threadId;
var myThread = new Thread(() => TestMethod("outpFile", y, out threadId));
myThread.Start();
myThread.Join();
//TestMethod("outpFile", y, out threadId);
}
stopWatch.Stop();
Console.WriteLine("Seconds Taken:\t{0}",stopWatch.Elapsed.TotalMilliseconds);
}

public static void TestMethod(string fileName, int hifi, out int threadId)
{
fileName = fileName + hifi;
var fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
var sw = new StreamWriter(fs, Encoding.UTF8);
for (int x = 0; x < 10000; x++)
{
sw.WriteLine(DateTime.Now.ToString());
}
sw.Close();
threadId = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("{0}",threadId);
}
}
}

现在,如果我注释代码的线程创建部分,并在一个循环中仅调用testMethod 10次,它比线程创建尝试处理的多个线程快。

最佳答案

代码的线程化版本正在做额外的工作,因此不必担心它的速度较慢。

当您执行以下操作时:

var myThread = new Thread(() => TestMethod("outpFile", y, out threadId));
myThread.Start();
myThread.Join();

...您正在创建一个线程,让它调用 TestMethod,然后等待它完成。 创建和启动线程的额外开销将使事情比不带任何线程的TestMethod慢。

如果启动所有线程,然后等待它们完成,则可能会看到更好的性能,例如:
var workers = new List<Thread>();
for (int i = 0; i < 10; ++i)
{
var y = x;
int threadId;
var myThread = new Thread(() => TestMethod("outpFile", y, out threadId));
myThread.Start();
workers.Add(myThread);
}
foreach (var worker in workers) worker.Join();

关于c# - 多线程并加快处理速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11317972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com