Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Question About C# and Static Classes and Functions

I've seen a lot of discussion about this subject on here.

If i have a static class w/ static methods that connects to a database or a server, is it a bad idea to use this in a multi-user environment (like a web page)? Would this make a new user's tread wait for previous users' threads to finish their calls before accepting a new one?

What would be the implications of this with multi-threading, also?

Thx!

like image 253
Micah Avatar asked Apr 23 '09 13:04

Micah


People also ask

What is unique about C?

Unlike most other modern languages such as Java, C++ and JavaScript, C does not provide a separate type for strings. A string is considered an array of characters terminated by a 0 character (denoted "\0"). The length of the string is denoted by a convention: the number of characters until the 0 character.

Why is C very important?

C is very fast in terms of execution time. Programs written and compiled in C execute much faster than compared to any other programming language. C programming language is very fast in terms of execution as it does not have any additional processing overheads such as garbage collection or preventing memory leaks etc.


2 Answers

If each static method is fully responsible for acquiring its resources and then disposing its resources within the scope of the method call (no shared state), then you shouldn't have any problem with threading that you wouldn't have using instance classes. I would suggest, however, that the bigger problem is that a reliance on public static methods (in static or non-static classes) creates many other design problems down the road.

  • First of all, you're binding very tightly to an implementation, which is always bad.
  • Second, testing all of the classes that depend on your static methods becomes very difficult to do, because you're locked to a single implementation.
  • Third, it does become very easy to create non-thread safe methods since static methods can only have static state (which is shared across all method calls).
like image 98
Michael Meadows Avatar answered Nov 08 '22 20:11

Michael Meadows


Static methods do not have any special behaviour in respect to multithreading. That is, you can expect several "copies" of the method running at the same time. The same goes for static variables - different threads can access them all at once, there is no waiting there. And unless you're careful, this can create chaos.

like image 40
Vilx- Avatar answered Nov 08 '22 19:11

Vilx-