Re: Static Functions in a Multi Threaded App

Tech-Archive recommends: Speed Up your PC by fixing your registry



SRLoka,

It all depends on what you are doing in the function. Just because you
arent accessing fields (static or instance), doesn't mean that you won't run
into threading issues.

Your best bet would be to place the MethodImpl attribute on the method,
passing the MethodImplOptions.Synchronized value into the constructor. This
will ensure that access to the Log method is synchronized.

If you created a separate class instance on each thread, it wouldn't
necessarily work, since they might all access the same file, and you could
end up interweaving the writes to the file in between each other (if you did
multiple writes per call to Log).

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- mvp@xxxxxxxxxxxxxxxxxxxxxxxxxxx

"Seenu" <Srinivas.Reddy.Loka@xxxxxxxxx> wrote in message
news:1118764208.995894.148090@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
> Is it safe to create a static function in a multi threaded application
> ? As an example, I have a function that logs errors ,exceptions and
> some informational data
> public static void Log(....)
> {
> //
> }
>
> There are multiple threads in this application that call this function.
> Is there any advantage if each thread creates an instance of the
> class(I would remove the static) and uses it ? The function itself does
> not access any instance variables. Will there be any thread saefty
> issues if it is static. ?
>
> Thank You
>
> SRLoka
>


.



Relevant Pages

  • Re: Share a read-only std::list between two threads
    ... safety guarantees of simple C types: ... do you have a hash table which cares about ... multiple threads at all makes such guarantee, ...
    (comp.programming.threads)
  • Re: Share a read-only std::list between two threads
    ... do you have a hash table which cares about ... A single object is thread safe for reading from multiple threads. ...
    (comp.programming.threads)
  • Re: threads and hashtable
    ... MSDN says that multiple threads doing reads is safe. ... is if my write thread is only adding new buckets to the ... the addmethod somehow modifies the general state of the hashtable ...
    (microsoft.public.dotnet.framework)
  • Re: 2 threading questions
    ... djc wrote: ... safe to *read* from multiple threads? ... thread safe you have to use one of the synchronization features to ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: 2 threading questions
    ... djc wrote: ... are all objects (value and reference type variables and objects/classes) ... safe to *read* from multiple threads? ... thread safe you have to use one of the synchronization features to ...
    (microsoft.public.dotnet.languages.csharp)