Are there cases when calling the native windows API, that I need to retry?

Brett Rader 21 Reputation points
2021-11-12T16:34:00.88+00:00

I am calling the windows api directly from C#, and I found an issue calling GetWindowDC(); we were not releasing the device context (ReleaseWindowsDC()), and therefore we exceeded the max number, which caused it to return 0. Having said that, it occurs to me that there might be other reasons this and other api calls fail (i.e. timing).

If I get a null back, should I call Marshal.GetLastWin32Error(), and then retry the call on certain circumstances? Are there any other API calls that I should consider doing retries on? If so, where can I find documentation on this?

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,428 questions
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 81,831 Reputation points
    2021-11-13T11:43:09.29+00:00

    For GDI DCs, the usual way that MS does is :

    IntPtr hDC = GetWindowDC(this.Handle);
    if (hDC != IntPtr.Zero)
    {
        // Code....
    
        ReleaseDC(this.Handle, hDC);
    }
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Xiaopo Yang - MSFT 11,501 Reputation points Microsoft Vendor
    2021-11-15T02:06:33.353+00:00

    Yes. GetLastError() and then according to the error code, you can retry the call at right time on your circumstance.

    1 person found this answer helpful.
    0 comments No comments