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

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

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.
1,890 questions
No comments
{count} votes

Accepted answer
  1. answered 2021-11-13T11:43:09.29+00:00
    Castorix31 65,366 Reputation points

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

    IntPtr hDC = GetWindowDC(this.Handle);
    if (hDC != IntPtr.Zero)
        // Code....
        ReleaseDC(this.Handle, hDC);
    No comments

1 additional answer

Sort by: Most helpful
  1. answered 2021-11-15T02:06:33.353+00:00
    Xiaopo Yang - MSFT 5,831 Reputation points Microsoft Employee

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

    No comments