写文件需要为交通繁忙优化 [英] write file need to optimised for heavy traffic
问题描述
我很新的C#,这是我的第一个问题,请对我温柔
i am very new to C#, and this is my first question, please be gentle on me
我试图写一个应用程序来捕获一些蜱数据数据提供者,以下是该计划的主要部分。
I am trying to write a application to capture some tick data from the data provider, below is the main part of the program
void zf_TickEvent(object sender, ZenFire.TickEventArgs e)
{
output myoutput = new output();
myoutput.time = e.TimeStamp;
myoutput.product = e.Product.ToString();
myoutput.type = Enum.GetName(typeof(ZenFire.TickType), e.Type);
myoutput.price = e.Price;
myoutput.volume = e.Volume;
using (StreamWriter writer = File.AppendText("c:\\log222.txt"))
{
writer.Write(myoutput.time.ToString(timeFmt) + ",");
writer.Write(myoutput.product + "," );
writer.Write(myoutput.type + "," );
writer.Write(myoutput.price + ",");
writer.Write(myoutput.volume + ",");
}
我已经成功地将数据写入到文本文件中,但是我知道,这个方法会被调用像10000次,第二次在高峰时间,并打开一个文件,并追加了很多次第二是非常低效的,我指出来使用缓冲区或某种,但我不知道如何做到这一点,我尝试阅读文档,但我仍然不明白,这就是为什么我这里寻求帮助。
i have successfully write the data into the text file, however i know that this method will be call like 10000 times a second during peak time, and open a file and append it many times a second is very inefficient, i was pointed to use a buffer or some sort, but i have no idea how to do it, i try reading the document but i still dont understand, thats why i turn in here for help.
请给我一些(工作)代码片段,所以我可以指着写方向。谢谢
Please give me some (working) snippet code so i can pointed to the write direction. thanks
编辑:我已经简化代码,尽可能
i have simplified the code as much as possible
using (StreamWriter streamWriter = File.AppendText("c:\\output.txt"))
{
streamWriter.WriteLine(string.Format("{0},{1},{2},{3},{4}",
e.TimeStamp.ToString(timeFmt),
e.Product.ToString(),
Enum.GetName(typeof(ZenFire.TickType), e.Type),
e.Price,
e.Volume));
}
ED告诉我,使我的流场,又是怎样的语法好像?任何人都可以张贴一些代码,以帮助我吗?非常感谢
ED has told me to make my stream to a field, how is the syntax looks like? can anyone post some code to help me? thanks a lot
推荐答案
我会用的String.Format:
I would use String.Format:
using (StreamWriter writer = new StreamWriter(@"c:\log222.txt", true))
{
writer.AutoFlush = true;
writer.Write(String.Format("{0},{1},{2},{3},{4},", myoutput.time.ToString(timeFmt),
myoutput.product, myoutput.type, myoutput.price, myoutput.volume);
}
如果您使用 @
字符串之前,您不必用双 \
。
If you use @
before string you don't have to use double \
.
这是更快 - 你写一次的文件,而不是5次,此外,您不使用 +
运营商,字符串这是不。最快的运行;)
This is much faster - you write only once to the file instead of 5 times. Additionally you don't use +
operator with strings which is not the fastest operation ;)
此外 - 如果这是多线程的应用程序 - 你应该考虑使用一些锁。这将阻止应用程序的尝试写入,例如从该文件。 2个线程在同一时间。
Also - if this is multithreading application - you should consider using some lock. It would prevent application from trying to write to the file from eg. 2 threads at one time.
这篇关于写文件需要为交通繁忙优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!