[英]C# WPF Show loading screen while socket sending and receiving data 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線程無法同時處理消息和執行代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.