Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

c# - Do I need to Dispose a SemaphoreSlim

According to the documentation:

"a SemaphoreSlim doesn't use a Windows kernel semaphore".

Are there any special resources used by the SemaphoreSlim which make it important to call Dispose when the SemaphoreSlim will no longer be used?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you access the AvailableWaitHandle property, then Yes, you must call Dispose() to cleanup unmanaged resources.

If you do not access AvailableWaitHandle, then No, calling Dispose() won't do anything important.

SemaphoreSlim will create a ManualResetEvent on demand if you access the AvailableWaitHandle. This may be useful, for example if you need to wait on multiple handles. If you do access the AvailableWaitHandle property, and then fail to call Dispose() you will have a leaked ManualResetEvent, which presumably wraps a handle to an unmanaged CreateEvent resource that needs a corresponding call to CloseHandle to clean up.

As other posters have pointed out, you should call Dispose() when you are done with any object that implements IDisposable. In this case, there are several risks to ignoring that practice, even though it may technically be safe to do so:

  1. My statements are based the reference source code to .NET 4.6.1. There is always the slim (pun intended) possibility that some future version of the framework will change SemaphoreSlim to where Dispose() is required.
  2. If your SemaphoreSlim is exposed outside of your class, calling code might reference the AvailableWaitHandle property not realizing that your class isn't disposing the SemaphoreSlim and create an unmanaged resource leak.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...