Android:连续轮询多个TCP服务器
我需要使用Xamarin.Android从多个Android设备连续轮询多个TCP服务器(嵌入式硬件),然后相应地更新UI。此外,这些安卓设备可以与服务器交互并更改设置。我使用了一个队列来管理来自这些多个设备的同步轮询和异步命令(下面的代码中没有显示) 我现在看到的是一个糟糕的同步实现,它有时会阻塞UI或重载垃圾收集。找不到任何与我的查询相关的资源。需要关于最佳方式的指导Android:连续轮询多个TCP服务器,android,asynchronous,xamarin.android,tcpclient,polling,Android,Asynchronous,Xamarin.android,Tcpclient,Polling,我需要使用Xamarin.Android从多个Android设备连续轮询多个TCP服务器(嵌入式硬件),然后相应地更新UI。此外,这些安卓设备可以与服务器交互并更改设置。我使用了一个队列来管理来自这些多个设备的同步轮询和异步命令(下面的代码中没有显示) 我现在看到的是一个糟糕的同步实现,它有时会阻塞UI或重载垃圾收集。找不到任何与我的查询相关的资源。需要关于最佳方式的指导 BlockingCollection<string[]> tcp_Queue = new BlockingCol
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, 0, data.Length);
Log.Verbose(tag, "Command: {0}", tcp_data[1]);
byte[] new_data = new byte[45];
int bytes = networkStream.Read(new_data, 0, new_data.Length);
responseData = Encoding.ASCII.GetString(new_data, 0, 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)
{
}
}
}
}
BlockingCollection tcp_Queue=new BlockingCollection();
CancellationTokenSource cts=新的CancellationTokenSource();
QueueUserWorkItem(o=>TCP_Communicator());
QueueUserWorkItem(o=>ScanServers());
...
void ScanServers()
{
while(true)
{
while(数据同步)
{
if(哈尔茨坎)
{
打破
}
如果(tcp_Queue.Count==0)
{
对于(int i=0;i
嘿,比拉尔!您应该可以查找任何C#轮询示例,例如@Saamer Thank。这当然对我的投票部分有所帮助。但是,我还必须处理来自用户的异步输入,因此我必须使用阻塞队列来管理对服务器的这两种类型的请求。如何在轮询中同时管理这两个问题