开发者

Async stream writing in a thread

I have a thread in which I write to 2 streams. The problem is that the thread is blocked until the first one finishes writing (until all data is transferred on the other side of the pipe), and I don't want that. Is there a way to make it asy开发者_开发知识库nchronous? chunkOutput is a Dictionary filled with data from multiple threads, so the faster checking for existing keys is, the faster the pipe will write.

void ConsumerMethod(object totalChunks) {
    while(true) {
        if (chunkOutput.ContainsKey(curChunk)) {
            if (outputStream != null && chunkOutput[curChunk].Length > 0) {
                outputStream.Write(chunkOutput[curChunk]); // <-- here it stops
            }

            ChunkDownloader.AppendData("outfile.dat",
                    chunkOutput[curChunk], chunkOutput[curChunk].Length);

            curChunk++;
            if (curChunk >= (int) totalChunks) return;
        }

        Thread.Sleep(10);
    }            
}


You can use the Async methods of Stream, such as BeginWrite. You can check the IAsyncResult returned to detect when the write has finished.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜