문제

What is the best practice (cs is a TCriticalSection)

I have seen this a lot

cs->Enter();
try {
}
__finally {
  cs->Leave();
}

but why not enter the critical section within the try block? Could it cause any issues?

try {
  cs->Enter();
}
__finally {
  cs->Leave();
}
도움이 되었습니까?

해결책

Do not call Leave() unless Enter() succeeds. If Enter() fails, calling Leave() could leave the cs in a bad state. This is generally the same rule you should follow for any code that needs to use try..__finally to manage resources. Allocate/Obtain the resource first, THEN enter the try block. Or else change the code to utilize RAII-based logic instead or using try..__finally at all.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top