Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : What if a static method is called from multiple threads?

In my Application I have a static method that is called from multiple threads at the same time. Is there any danger of my data being mixed up?

In my first attempt the method was not static and I was creating multiple instance of the class. In that case my data got mixed up somehow. I am not sure how this happens because it only happens sometimes. I am still debugging. But now the method is static on I have no problems so far. Maybe it's just luck. I don't know for sure.

like image 380
TalkingCode Avatar asked Jun 14 '10 13:06

TalkingCode


People also ask

Bahasa C digunakan untuk apa?

Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.

C dalam Latin berapa?

C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).

Bahasa C dibuat pertama kali oleh siapa dan tahun berapa?

Bahasa pemrograman C ini dikembangkan antara tahun 1969 – 1972 oleh Dennis Ritchie. Yang kemudian dipakai untuk menulis ulang sistem operasi UNIX. Selain untuk mengembangkan UNIX, bahasa C juga dirilis sebagai bahasa pemrograman umum.


1 Answers

Variables declared inside methods (with the possible exception of "captured" variables) are isolated, so you won't get any inherent problems; however, if your static method accesses any shared state, all bets are off.

Examples of shared-state would be:

  • static fields
  • objects accessed from a common cache (non-serialized)
  • data obtained via the input parameters (and state on those objects), if it is possible that multiple threads are touching the same object(s)

If you have shared state, you must either:

  • take care not to mutate the state once it can be shared (better: use immutable objects to represent state, and take a snapshot of the state into a local variable - i.e. rather than reference whatever.SomeData repeatedly, you read whatever.SomeData once into a local variable, and then just use the variable - note that this only helps for immutable state!)
  • synchronize access to the data (all threads must synchronize) - either mutually exclusive or (more granular) reader/writer
like image 118
Marc Gravell Avatar answered Oct 15 '22 16:10

Marc Gravell