C# - 通过网络流接收文件阻止了WPF UI [英] C# - receiving a file through network stream is blocking WPF UI

查看:72
本文介绍了C# - 通过网络流接收文件阻止了WPF UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨。


我有这种接收文件的方法。

公共任务下载(IProgress< int> downloadProgress)
{
返回Task.Run

async()=>
{
var counter = 0;

var buffer = new byte [1024];

while(true)
{
var byteCount = await _networkStream.ReadAsync( buffer,0,buffer.Length);

counter + = byteCount;
downloadProgress.Report(counter);

if(byteCount!= buffer.Length)
休息;
}
}
);
}

然后在UI中我调用

 await StartDownloading(progress); 

其中进度只是更新标签。


当我运行它时,它会阻止UI。我不知道为什么,Task.Run()不应该在一个单独的线程上运行任务吗?


我该如何解决?




解决方案

您好,



 这是一个旧帖子的链接,似乎有您的问题;



  https://social.msdn.microsoft.com/Forums/sqlserver/en-US/d22af66c-cbdb-4866-8d14 -19c1abfdc71d / wpf-c-using-tasks?forum = wpf



 希望这会有所帮助:)


Hi.

I have this method for receiving a file.

public Task Download(IProgress<int> downloadProgress)
{
    return Task.Run
    (
        async () =>
        {
            var counter = 0;

            var buffer = new byte[1024];

            while (true)
            {
                var byteCount = await _networkStream.ReadAsync(buffer, 0, buffer.Length);

                counter += byteCount;
                downloadProgress.Report(counter);

                if (byteCount != buffer.Length)
                    break;
            }
        }
    );
}

Then in the UI I call

await StartDownloading(progress);

where progress is simply updating a label.

When I run it, it blocks UI. I have no idea why, shouldn't Task.Run() make task running on a seperate thread?

How do I fix it please?

解决方案

Hello,

 Here is a link to an older posting that seems to have had your issue;

 https://social.msdn.microsoft.com/Forums/sqlserver/en-US/d22af66c-cbdb-4866-8d14-19c1abfdc71d/wpf-c-using-tasks?forum=wpf

 Hope this helps :)


这篇关于C# - 通过网络流接收文件阻止了WPF UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆