0

什么是最佳实践(cs 是 TCriticalSection)

我见过很多

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

但是为什么不在 try 块中进入临界区呢?它会引起任何问题吗?

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

1 回答 1

2

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.

于 2013-09-11T15:28:29.960 回答