abh*_*bhi 1 .net c# multithreading
我有以下代码.我希望在多个线程上启动文件创建.目标是当我在多个线程上创建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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我评论代码的线程创建部分并且只是在循环中调用testMethod 10次,那么它比线程创建尝试处理的多个线程更快.
你的代码的线程版本正在做额外的工作,所以它的速度慢并不令人惊讶.
当你做类似的事情时:
var myThread = new Thread(() => TestMethod("outpFile", y, out threadId));
myThread.Start();
myThread.Join();
Run Code Online (Sandbox Code Playgroud)
...你正在创建一个线程,让它调用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();
Run Code Online (Sandbox Code Playgroud)