使用终止处理程序
以下示例演示如何使用终止处理程序来确保在执行受保护的代码正文终止时释放资源。 在本例中,线程使用 EnterCriticalSection 函数来等待关键节对象的所有权。 线程执行完受关键节保护的代码后,它必须调用 LeaveCriticalSection 函数,以使关键节对象可供其他线程使用。 使用终止处理程序可保证这种情况发生。 有关详细信息,请参阅关键节对象。
LPTSTR lpBuffer = NULL;
CRITICAL_SECTION CriticalSection;
// EnterCriticalSection synchronizes code with other threads.
EnterCriticalSection(&CriticalSection);
__try
{
// Perform a task that may cause an exception.
lpBuffer = (LPTSTR) LocalAlloc(LPTR, 10);
StringCchCopy(lpBuffer, 10, TEXT("Hello"));
_tprintf(TEXT("%s\n"),lpBuffer);
LocalFree(lpBuffer);
}
__finally
{
// LeaveCriticalSection is called even if an exception occurred.
LeaveCriticalSection(&CriticalSection);
}
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈