[英]Console.Writeline from EventHandler
I've written a simple async TCP-Server - it works well. 我已经编写了一个简单的异步TCP服务器-效果很好。 But now I want to make an output of the received Data on the Console-Testprogram.
但是现在我想在Console-Test程序上输出接收到的数据。 And the problem is, this isn't working!
问题是,这不起作用! If I connect the MainThread to the EventHandler the program does nothing.
如果我将MainThread连接到EventHandler,则该程序将不执行任何操作。 Debug is showing that the sc05Server_DataAvailable was called but then nothing happened.
调试显示sc05Server_DataAvailable被调用,但是什么也没发生。 The program is still responsive.
该程序仍然响应。
Here The Code: 这里的代码:
private void ReadCallback(IAsyncResult asyncResult)
{
Sc05BdClient sc05BdClient = asyncResult.AsyncState as Sc05BdClient;
if (sc05BdClient == null) return;
NetworkStream networkStream = sc05BdClient.NetworkStream;
int read = networkStream.EndRead(asyncResult);
if (read == 0)
{
lock (clients)
{
clients.Remove(sc05BdClient);
return;
}
}
string data = Encoding.GetString(sc05BdClient.Buffer, 0, read);
System.Diagnostics.Debug.Print(data);
OnDataAvailable(this, new DataAvailableEventArgs(data)); <---- here Handler is called
networkStream.BeginRead(sc05BdClient.Buffer, 0, sc05BdClient.Buffer.Length, ReadCallback, sc05BdClient);
}
public event EventHandler<DataAvailableEventArgs> DataAvailable;
protected virtual void OnDataAvailable(object sender, DataAvailableEventArgs e)
{
EventHandler<DataAvailableEventArgs> handler = DataAvailable;
if (handler != null)
handler(sender, e);
}
public class DataAvailableEventArgs : EventArgs
{
public string Data;
public DataAvailableEventArgs(string data)
{
Data = data;
}
}
The Main program: 主程序:
class Program
{
static void Main()
{
Sc05BdServer sc05BdServer = new Sc05BdServer(IPAddress.Any, 2006);
sc05BdServer.DataAvailable += sc05BdServer_DataAvailable;
sc05BdServer.Start();
Console.ReadKey();
sc05BdServer.Stop();
}
static void sc05BdServer_DataAvailable(object sender, DataAvailableEventArgs e)
{
Console.WriteLine(e.Data); <--- this is called once
}
}
I think it has something to do with Threading - but I have no idea how to work with them. 我认为这与线程有关-但我不知道如何使用它们。
You are probably experiencing some kind of race issue although Console should be immune to that. 尽管Console应该可以避免这种情况,但是您可能正在遇到某种种族问题。 Check this question but note that I couldn't reproduce the problem: Strange behaviour of Console.ReadKey() with multithreading
检查此问题,但请注意,我无法重现该问题: Console.ReadKey()具有多线程的奇怪行为
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.