You won't get better performance by using a bunch of threads. And you'll
have to handle the case of two writers interacting with each other resulting
in bits and pieces of messages being interspersed. Especially if you are
unfamiliar with threading, use a single thread to do the writing and send
messages to it from any thread that wants to do logging. This will remove
the time taken to write the file from the main thread, which I presume is
what you mean by getting better performance. To communicate from other
threads to the logging thread, I would suggest a queue class that you write
yourself, based on Queue<string>, probably (to store the messages to be sent
to the file), and an event which is fired when there are messages in the
queue. Any thread in the application can then call:
// Log a string.
theQueue.Enqueue( "Here is some text to be written to the file" );
Then, you need a logging thread to remove items from the queue when they
appear and write them to the log file. You have to start this thread early
on:
// Create logging thread.
exitNow = false;
loggingThread = new Thread( new ThreadStart( this.ThreadProc ) );
loggingThread.Start();
The logging thread itself might look something like this:
// Open the file.
// Seek to the beginning and clear the data or seek to the end to append.
// Loop as long as the main thread doesn't tell us to exit.
while ( theQueue.Wait() && !exitNow )
{
// Get the next message from the queue.
string msg = theQueue.Dequeue();
// Write it to the file.
}
Obviously, I'm not going to write all the code for you, but I hope that you
get the idea.
Paul T.
<(E-Mail Removed)> wrote in message
news:c395a955-2388-459d-909b-(E-Mail Removed)...
> Hello NG,
>
> in my application i log many events or functions (with duration time)
> in a text file, so that i can reproduce if an exception was fired. It
> works fine.
>
> Now i want to use a thread (or many threads) for writing into the text
> file to get better performance. But i have no experience using thread.
> What will i have to use? ThreadPool or Queue or ThreadWrapperBase?
>
> Maybe someone has an example for me?
>
> Regards, Verena
|