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 i开发者_C百科t 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?
- 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. Logging is a standard task and there is no need to reinvent the wheel.
- 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.
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.
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
}
精彩评论