(MSDN)花费大量时间进行循环运行(ReadFile,WriteFile,Overlapped结构)

时间:2018-07-03 13:12:07

标签: readfile msdn serial-communication writefile overlapped-io

我的目标是使用MSDN API从A读取dataBuffer并将数据重复写入设备B。我正在使用ReadFileEx和WriteFileEx来请求重叠的I / O读写,因此使用ReadFile和WriteFile的原始耗时的for循环现在可以进入后台,并且UI主线程可以一直响应。

我首先创建结构MY_OVERLAPPED,该结构继承自OVERLAPPED,并添加了两个以上的元素,event是指向MyClass的指针,该指针可以帮助访问该类中的变量,句柄,dataBuffer等,并且count分别用于重置Offset值ReadFileEx调用之前的时间。读取位置为count * 524288,因为我每次读取524288字节并存储在dataBuffer中。

我的问题是: 1.如何不使用继承的OVERLAPPED结构的Offset元素来更改读取位置,例如使用引用计数?

2。以下代码无法按照我的方式工作。 ReadCompletionRoutine只能运行一次,最终会收到非常长的偏移号。现在,我假设这是问题所在,并且首先关注它,所以请随时纠正我的任何代码结构。

我的代码流是: 1.将读取点设置为0 2.调用重叠的ReadFileEx 3.将调用ReadCompletion,将使用重叠的WriteFileEx写入读取的数据 4.将调用WriteCompletion,将指针设置为下一个524288字节并读取 5.(依此类推)两个完成例程将互相调用,直到所有数据都被传输

MyClass.h

struct MY_OVERLAPPED: OVERLAPPED {
    MyClass *event;
    unsigned long long count;
};

MyClass.cpp-主

MY_OVERLAPPED overlap;
memset(&overlap, 0,sizeof(overlap));

//point to this class (MyClass), so all variables can later be accessed
overlap.event = this; 

//set read position******how do I not use Offset??
overlap.Offset = 0;
overlap.OffsetHigh = 0;
overlap.count = 0;

//start the first read io request, read 524288 bytes, which 524288 bytes will be written in ReadCompletionRoutine
ReadFileEx(overlap.event->hSource, overlap.event->data, 524288, &overlap, ReadCompletionRoutine);

SleepEx(0,TRUE);

MyClass.cpp-回调

void CALLBACK ReadCompletionRoutine(DWORD errorCode, DWORD bytestransfered, LPOVERLAPPED lpOverlapped)
{
    //type cast to MY_OVERLAPPED
    MY_OVERLAPPED *overlap = static_cast<MY_OVERLAPPED*>(lpOverlapped);

    //write 524288 bytes and continue to read next 524288 bytes in WriteCompletionRoutine
    WriteFileEx(overlap->event->hDevice, overlap->event->data, 524288, overlap, WriteCompletionRoutine);
}

void CALLBACK WriteCompletionRoutine(DWORD errorCode, DWORD bytestransfered, LPOVERLAPPED lpOverlapped)
{
    MY_OVERLAPPED *overlap = static_cast<MY_OVERLAPPED*>(lpOverlapped);

    //set new offset to 524288*i, i = overlap->count for next block reading
    overlap->count = (overlap->count)+1;
    LARGE_INTEGER location;
    location.QuadPart = 524288*(overlap->count);
    overlap->Offset = location.LowPart;
    overlap->OffsetHigh = location.HighPart;

    ReadFileEx(overlap->event->hSource, overlap->event->data, 524288, overlap, ReadCompletionRoutine);
}

0 个答案:

没有答案
相关问题