我需要使用Xamarin.Android从多个Android设备连续轮询多个TCP服务器(嵌入式硬件),然后相应地更新UI。而且,这些Android设备可以与服务器交互并更改设置。我已经使用队列来管理来自这些多个设备的同步轮询以及异步命令(以下代码未显示)。
我现在拥有的是一个糟糕的同步实现,有时会阻塞UI或使垃圾回收超载。找不到与我的查询有关的任何资源。需要有关最佳方法的指导。
BlockingCollection<string[]> tcp_Queue = new BlockingCollection<string[]>();
CancellationTokenSource cts = new CancellationTokenSource();
ThreadPool.QueueUserWorkItem(o => TCP_Communicator());
ThreadPool.QueueUserWorkItem(o => ScanServers());
...
void ScanServers()
{
while (true)
{
while (datasync)
{
if (haltscan)
{
break;
}
if (tcp_Queue.Count == 0)
{
for (int i = 0; i < ips.Length; i++)
{
if (Array.IndexOf(unreachable_IPs,ips[i]) == -1)
{
tcp_Queue.Add(new string[] { ips[i],query_command });
}
}
}
}
}
}
void TCP_Communicator()
{
while (true)
{
while (datasync)
{
try
{
string[] tcp_data = tcp_Queue.Take(cts.Token); // A queue containing the IPs and command frame
using (var tcpClient = new TcpClient())
{
try
{
tcpClient.SendTimeout = 1000;
tcpClient.ReceiveTimeout = 1000;
tcpClient.NoDelay = true;
tcpClient.Connect(tcp_data[0],80);
using (var networkStream = tcpClient.GetStream())
{
Log.Verbose(tag,"Ping Success: " + tcp_data[0]);
try
{
byte[] data = Encoding.ASCII.GetBytes(tcp_data[1]);
networkStream.Write(data,data.Length);
Log.Verbose(tag,"Command: {0}",tcp_data[1]);
byte[] new_data = new byte[45];
int bytes = networkStream.Read(new_data,new_data.Length);
responseData = Encoding.ASCII.GetString(new_data,bytes);
Log.Verbose(tag,"Response: {0}",responseData);
}
catch (TimeoutException)
{
Console.WriteLine("TimeoutException");
responseData = string.Empty;
}
catch (IOException e)
{
Console.WriteLine("IOException" + e);
responseData = string.Empty;
}
}
}
catch (SocketException)
{
Log.Verbose(tag,"Ping Timeout: " + tcp_data[0]);
responseData = string.Empty;
}
}
Check_ScanResults(tcp_data,responseData);
}
catch (System.OperationCanceledException)
{
}
}
}
}