Should I use static function in c# where many calls the same func?

瘦欲@ 提交于 2019-12-23 17:10:11

问题


John's console application calls my DLL function many times (~15x per sec). I am thinking to put this function as a static method.

I know that :

  1. It can only access static props and objects.
  2. It doesn't need an instance to run the function.

But I don't know if these are the only questions which i need to ask myself.

Each John's calls to my function is in a new thread that he creates.

  • If there is an error in my function, how will this affect all other calls?
  • Should I make this function a regular function with instance to the class (which John will create)?
  • What about GC?

What is the best practice answer for this question?


回答1:


Sounds like there could be a problem. Calling a method which operates on static (shared) objects in a multithread environment should ring some alert bells for you.

Review your code and if there's a chance that a shared object is accessed from two (or more) threads at the same time, make the object an instance field and make your methods instance methods.

Of course, whether or not there is a risk depends much on the actual code (which you don't show) but making all calls nonstatic means that you lower the potential risk.




回答2:


Generally, if your static method doesn't use any state (i.e. both reading and writing to static fields and properties, or calling other static methods that do so), there won't be any side effects for the caller, no matter how many threads they start.

If you're asking for best practice, static methods are mostly a bad idea though. If at all, static methods should be only used for very generic utility functionality.

It's not recommended because you can't predict if requirements change and you need some state one day. Then you'd better use a class that the caller can instantiate, and you'll break all existing code that uses your function.

About garbage collection, yes sure that has some overhead, but that is currently the sacrifice if you go the route of memory-managed OO. If you want more control, use unsafe code or a language like C++ or Vala.




回答3:


I would agree with Wiktor (+1), but would also add that if synchronization is required in the static method, it may be more efficient to use multiple instances. Otherwise, having many threads might be pointless as only one can access a critical section at a time.



来源:https://stackoverflow.com/questions/8370144/should-i-use-static-function-in-c-sharp-where-many-calls-the-same-func

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!