The final result I got is not much different from the answers you got in other threads, and it may disappoint you a bit.
I'm thinking about whether you really need to use async-await.
Your current problem is a multi-producer single-consumer situation.
Couldn't the producer call a simple Add method and the consumer call the Take method?
Are there any unexpected errors in your actual tests?
Update:
It might look like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
TcpListener server;
BlockingCollection<root> bc;
public void InitListening()
{
bc = new BlockingCollection<root>();
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
}
public void Add(root data)
{
Task t2 = Task.Run(() =>
{
bc.Add(data);
});
}
public void Take()
{
Task.Run(() =>
{
try
{
while (true)
{
Console.WriteLine("Take" + bc.Take());
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
});
}
private void StartLisBtn_Click(object sender, RoutedEventArgs e)
{
server.Start();
Byte[] bytes = new Byte[256];
String data = null;
Task.Run(() =>
{
while (true)
{
Console.Write("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
XmlSerializer serializer = new XmlSerializer(typeof(root));
MemoryStream memStream = new MemoryStream(bytes);
root result = (root)serializer.Deserialize(memStream);
Add(result);
}
client.Close();
}
});
}
private void StopLisBtn_Click(object sender, RoutedEventArgs e)
{
server.Stop();
}
private void TakeBtn_Click(object sender, RoutedEventArgs e)
{
Take();
//If you need to write changes to the xml file, enable the following code.
//XmlDocument doc = new XmlDocument();
//doc.Load(@"D:\test\xml\out.xml");
//XmlNode root = doc.DocumentElement;
//XmlNodeList myNodeList = root.SelectNodes("//book/title");
//XmlNode myNode = myNodeList.Cast<XmlNode>().Where(n => n.Attributes["pro"].Value == "false").FirstOrDefault();
//myNode.Attributes[0].Value = "true";
//doc.Save(@"D:\test\xml\out.xml");
}
}
But there may be some omissions in the actual situation. If an error occurs, we can discuss the specific error.
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.