我正在构建一个WPF应用程序,该应用程序使用套接字在服务器之间来回传输数据。 问题:从服务器发送和接收数据时,屏幕被冻结,我想添加一个简单的加载动画,以便最终用户可以知道它当前正在加载,但是我不知道如何
我的C#套接字代码:
<?php
namespace Solarium;
use Solarium;
require 'vendor/autoload.php';
require(__DIR__.'\solarium\init.php');
htmlHeader();
// check solarium version available
echo 'Solarium library version: ' . Client::VERSION . ' - ';
// create a client instance
$config = array(
'endpoint' => array(
'localhost' => array(
'host' => 'localhost',
'port' => 3306,
'path' => '/solarium/',
)
)
);
$client = new Solarium\Client($config);
// create a ping query
$ping = $client->createPing();
// execute the ping query
try {
$result = $client->ping($ping);
echo 'Ping query successful';
echo '<br/><pre>';
var_dump($result->getData());
echo '</pre>';
} catch (Solarium\Exception $e) {
echo 'Ping query failed';
}
htmlFooter();
,然后在窗口中按一个名为“ login.xaml”的按钮,然后在检查数据正常后,调用它,它关闭当前窗口并初始化dashboard.xaml。 与服务器通信时,我只需要添加动画即可。
谢谢!
答案 0 :(得分:2)
在后台线程上调用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线程无法同时处理消息和执行代码。