c# - C# WPF 在套接字发送和接收数据时显示加载屏幕 C#
问题描述
我正在构建一个 WPF 应用程序,它使用套接字将数据传入和传出服务器。问题:在从服务器发送和接收数据时,屏幕被冻结,我想添加一个简单的加载动画,以便最终用户知道它当前正在加载,但我不知道如何
我的 C# 套接字代码:
public static string SendRecOne(string dataToSvr)
{
TcpClient client = new TcpClient(SERVER_NAME, PORT);
#region SendRequest
int ByteCount = Encoding.ASCII.GetByteCount(dataToSvr); //How much bytes?
byte[] ByteBuffer = new byte[1024]; //initialize byte array
ByteBuffer = Encoding.ASCII.GetBytes(dataToSvr);
NetworkStream stream = client.GetStream();
stream.Write(ByteBuffer, 0, ByteBuffer.Length);
#endregion
#region Receive Response
//byte[] responseData = new byte[client.ReceiveBufferSize];
//int bytesRead = stream.Read(responseData, 0, client.ReceiveBufferSize);
int i;
string ToReturn = null;
ByteBuffer = new byte[ByteBuffer.Length];
MemoryStream ms = new MemoryStream();
while (true)
{
if (stream.DataAvailable)
{
while ((i = stream.Read(ByteBuffer, 0, ByteBuffer.Length)) != 0)
{
ms.Write(ByteBuffer, 0, ByteBuffer.Length);
if (stream.DataAvailable)
continue;
else
break;
}
ToReturn = Encoding.ASCII.GetString(ms.ToArray());
return ToReturn;
}
}
#endregion
我在按下窗口中名为“login.xaml”的按钮后调用它,并在检查数据正常后,它关闭当前窗口并初始化dashboard.xaml。我只需要在与服务器通信时添加一个动画。
谢谢!
解决方案
在后台线程上调用您的SendRecOne
方法或使用 *Async 重载使其异步:
public static async Task<string> SendRecOne(string dataToSvr)
{
progressBar.Visibility = Visibility.Visible;
string ToReturn = null;
using (TcpClient client = new TcpClient(SERVER_NAME, PORT))
{
int ByteCount = Encoding.ASCII.GetByteCount(dataToSvr); //How much bytes?
byte[] ByteBuffer = new byte[1024]; //initialize byte array
ByteBuffer = Encoding.ASCII.GetBytes(dataToSvr);
NetworkStream stream = client.GetStream();
await stream.WriteAsync(ByteBuffer, 0, ByteBuffer.Length);
//byte[] responseData = new byte[client.ReceiveBufferSize];
//int bytesRead = await stream.ReadAsync(responseData, 0, client.ReceiveBufferSize);
int i;
ByteBuffer = new byte[ByteBuffer.Length];
MemoryStream ms = new MemoryStream();
if (stream.DataAvailable)
{
while ((i = await stream.ReadAsync(ByteBuffer, 0, ByteBuffer.Length)) != 0)
{
await ms.WriteAsync(ByteBuffer, 0, ByteBuffer.Length);
if (!stream.DataAvailable)
break;
}
ToReturn = Encoding.ASCII.GetString(ms.ToArray());
}
progressBar.Visibility = Visibility.Collapsed;
}
return ToReturn;
}
XAML:
<ProgressBar x:Name="progressBar" IsIndeterminate="True" />
UI 线程不能同时处理消息和执行您的代码。
推荐阅读
- javascript - 我如何更改它之外的样式表属性?反应原生
- python - 使用 BeautifulSoup 获取搜索结果编号
- ocaml - 如何根据 OCAML 中的上下文使参数采用伪“null”值
- google-cloud-firestore - 如何将集合转换为 Firestore 安全规则中的列表?
- docker - 启用 HTTPS 后,traefik 没有响应
- list - 在批处理程序中制作自定义文本列表
- c# - ASP.NET Core 3.1 与 npm 的集成
- javascript - 进行 AJAX 调用时,如何在请求标头中发送 JSON Web 令牌?
- spyder - 如何在 Spyder 中显示指南?
- reactjs - 什么会阻止我使用 Session over JWT 进行 API 身份验证(对于 express 和 reactjs 应用程序)