C# 写文件需要针对高流量进行优化第4部分
这是第3部分的延续 由于我的代码有所更改,我认为最好打开一个新线程C# 写文件需要针对高流量进行优化第4部分,c#,multithreading,performance,io,C#,Multithreading,Performance,Io,这是第3部分的延续 由于我的代码有所更改,我认为最好打开一个新线程 public class memoryStreamClass { static MemoryStream ms1 = new MemoryStream(); static MemoryStream ms2 = new MemoryStream(); static int c = 1; public void fillBuffer(string o
public class memoryStreamClass
{
static MemoryStream ms1 = new MemoryStream();
static MemoryStream ms2 = new MemoryStream();
static int c = 1;
public void fillBuffer(string outputString)
{
byte[] outputByte = Encoding.ASCII.GetBytes(outputString);
if (c == 1)
{
ms1.Write(outputByte, 0, outputByte.Length);
if (ms1.Length > 8100)
{
c = 2;
Thread thread1 = new Thread(() => emptyBuffer(ref ms1));
thread1.Start();
}
}
else
{
ms2.Write(outputByte, 0, outputByte.Length);
if (ms2.Length > 8100)
{
c = 1;
Thread thread2 = new Thread(() => emptyBuffer(ref ms2));
thread2.Start();
}
}
}
void emptyBuffer(ref MemoryStream ms)
{
FileStream outStream = new FileStream(string.Format("c:\\output.txt", FileMode.Append);
ms.WriteTo(outStream);
outStream.Flush();
outStream.Close();
ms.SetLength(0);
ms.Position = 0;
Console.WriteLine(ms.Position);
}
与第3部分中的代码相比,我改变了两件事
对我的代码有什么意见吗?问题仍然是静态的。您正在清除可能包含未写入磁盘的数据的缓冲区 我认为这种情况有1.4%的时间发生 ms1 fills up, empty buffer1 thread started, switch to ms2 empty buffer1 is writing to disk ms2 fills up, empty buffer2 thread started, switch to ms1 empty buffer1 to disk finishes ms1 is cleared while it is the active stream ms1已满,空缓冲区1线程已启动,切换到ms2 空缓冲区1正在写入磁盘 ms2已满,空缓冲区2线程已启动,切换到ms1 空缓冲区1到磁盘结束 ms1是活动流时被清除 在进行多线程编程时,静态类可以,但静态类不行。理想情况下,线程之间没有共享内存,代码完全依赖于它
这样想吧——如果你希望某个值持续变化,那它就不完全是这样了?我看了这一问题之前的所有部分,看起来你没有实际问题。你只需预测一个问题,并尝试先发制人地解决它。首先,以最简单的形式实现它,找出“实际”问题,从中派生出需求,并尝试满足该需求。解决这个问题会容易得多,因为这样用户会有更大的想法空间。我的印象是,如果我的变量不是静态的,每次都会有一个新变量,这样我就无法填充memorystream并将其输出到文件中,我错了吗?我将变量更改为非静态变量,根本无法执行写入操作,我猜每次都会重新声明变量,并且从不填充,因此也不会写入文件。我尝试更改缓冲区大小,看看性能是否有所提高