简体   繁体   English

关于在C#中使用内存流的性能问题

[英]Regarding performance issues for usage of memory stream in c#

I created one project. 我创建了一个项目。 Many persons will use my project at a time. 很多人一次会使用我的项目。 If any person got error then it will write to a file by creating object using memory stream. 如果有人出错,它将通过使用内存流创建对象来写入文件。 If everybody get errors, then that number of objects will be created and all objects are writing error to the same file at a time. 如果每个人都出错,那么将创建该数量的对象,并且所有对象一次都将错误写入同一文件。 Is there any problems and performance issues with this? 这有什么问题和性能问题吗?

  1. Using a memory stream for writing to a file seems unnecessary. 似乎不需要使用内存流来写入文件。 Open/create the file and write directly to the file. 打开/创建文件,然后直接写入文件。 Even better: Use a library for logging such as log4net which will take care of simultaneous access to the log file. 更好的是: 使用诸如log4net之类的日志记录库,该库将负责同时访问日志文件。 Logging is a standard task and there is no need to reinvent the wheel. 日志记录是一项标准任务,无需重新发明轮子。
  2. If you are worried about performance do a load test and see whether there actually is a problem. 如果你担心性能做负载测试 ,看看是否有其实一个问题。

A memory stream is just a Stream interface around a byte array. 内存流只是字节数组周围的Stream接口。

So this is actually very fast. 因此,这实际上非常快。

But the whole byte array is kept in memory, so the performance issues you might have, are due to too much memory allocation. 但是整个字节数组都保留在内存中,所以可能由于内存分配过多而导致性能问题。

If you really will have problems depends on how big "many persons" is, and the amount of data in the memory stream. 您是否真的会遇到问题取决于“多人”有多大,以及内存流中的数据量。

Also be lookout for locking problems, if you write to the same file with "many persons". 如果用“许多人”写入同一文件,也要注意锁定问题。

File locking/contention comes to mind. 想到文件锁定/争用。 Could you not create a log directory and have all log writes create their own file? 您不能创建日志目录,并让所有日志写入都创建自己的文件吗? Alternatively, use the .NET tracing functionality, or something like log4net, Common.Logging, dotTrace as a logging framework to remove these concerns for you. 另外,也可以使用.NET跟踪功能或类似log4net,Common.Logging,dotTrace之类的日志记录框架来为您消除这些问题。

Make the stream shared and use a lock around it while accessing log file. 访问日志文件时,共享流并在其周围使用锁。 Remember to close the stream on exit. 请记住在退出时关闭流。

static Object _locker = new Object;
static FileStream fs = new FileStream(...);

// your code
lock(_locker)
{
   fs.Write(...) // write to stream
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM