流异步读/写冻结UI线程

时间:2017-05-28 20:57:25

标签: c# asynchronous tcp filestream networkstream

我遇到Read()上的异步Write()FileStream/NetworkStream方法的问题。

在我的程序中,我正在向服务器发送文件,我不希望文件上传操作冻结主线程,所以我使用ReadAsyncWriteAsync函数,但有些东西是仍在冻结UI线程。

以下是代码:

public async Task SendFile(File file)
{
    if (socket == null || !socket.Connected) throw new Exception();

    using (NetworkStream networkStream = new NetworkStream(socket, FileAccess.Write, false))
    using (FileStream fStream = new FileStream(file.Path, FileMode.Open, FileAccess.Read, FileShare.None, 4096, useAsync: true))
    {
        byte[] buffer = new byte[8192]; 
        int read = 0;

         while ((read = await fStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
         {
             await networkStream.WriteAsync(buffer, 0, read);
         }
         await networkStream.FlushAsync();
    }
}

我致电SendFile(File file)的部分:

private async void SendForm_Shown(object sender, EventArgs e)
{
    FileSender fileSender = new FileSender();
    Queue<Computer> receiverQueue = new Queue<Computer>(receivers);

    while (receiverQueue.Count > 0)
    {
        Computer recv = receiverQueue.Dequeue();
        await fileSender.Connect(recv);
        bool approved = await fileSender.RequestFileSend(file);
        if (!approved)
        {
            continue;
        }
        await fileSender.SendFile(file);
        await fileSender.Disconnect();
    }

}

0 个答案:

没有答案