异步机制 - BindIoCompletionCallback

直接上代码

VOID CALLBACK test_io_completion_routine(

  DWORD dwErrorCode,

  DWORD dwNumberOfBytesTransfered,

  LPOVERLAPPED lpOverlapped

)

{

         printf("dwErrorCode %d, dwNumberOfBytesTransfered %d\n", dwErrorCode, dwNumberOfBytesTransfered);

         printf("%s\n", (char*)(lpOverlapped + 1));

 

         free(lpOverlapped);

}

 

BOOL

queue_read_req(

    HANDLE hFile,

         DWORD nNumberOfBytesToRead,

         DWORD Offset)

{

         BOOL bResult = FALSE;

         OVERLAPPED* olv = (OVERLAPPED* )malloc(sizeof(OVERLAPPED) + nNumberOfBytesToRead);

         if(olv)

         {

                   DWORD nBytesRead = 0;

                   ZeroMemory(olv, sizeof(OVERLAPPED) + nNumberOfBytesToRead);

 

                   olv->Offset = Offset;

                   bResult = ReadFile(hFile, (void*)(olv + 1), nNumberOfBytesToRead, &nBytesRead, olv) ;

                   if (!bResult)

                   {

                            DWORD dwError = 0;

                            switch (dwError = GetLastError())

                            {

                            case ERROR_HANDLE_EOF:

                                     free(olv);

                                     break;

                            case ERROR_IO_PENDING:

                                     break;

                            default:

                                     break;

 

                            }

                   }

 

         }

 

         return bResult;

}

 

void test_io_port()

{

         LPCWSTR FileTest = L"C:\\NTDLL.txt";

         HANDLE hFile = CreateFileW(FileTest,               // file to open

                   GENERIC_READ,          // open for reading

                   FILE_SHARE_READ,       // share for reading

                   NULL,                  // default security

                   OPEN_EXISTING,         // existing file only

                   FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, // normal file

                   NULL); // no attr. template

         if(hFile != INVALID_HANDLE_VALUE)

         {

                   BindIoCompletionCallback(hFile, test_io_completion_routine, 0);

 

                   for(int i = 0; i < 5; i++)

                   {

                            queue_read_req(hFile, 1024, i*1024 );

                   }

 

                   Sleep(5000);

 

                   CloseHandle(hFile);

         }

 

}

posted @ 2015-04-10 17:42  sysnap  阅读(748)  评论(0编辑  收藏  举报