8

我写了一个简单的异步 TCP-Server - 它运行良好。但现在我想在控制台测试程序上输出接收到的数据。问题是,这行不通!如果我将 MainThread 连接到 EventHandler 程序什么也不做。调试显示 sc05Server_DataAvailable 被调用,但没有发生任何事情。该程序仍然响应。

这里的代码:

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;
    }
}

主程序:

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
    }
}

我认为这与线程有关 - 但我不知道如何使用它们。

4

1 回答 1

3

尽管控制台应该对此免疫,但您可能会遇到某种种族问题。检查这个问题,但请注意我无法重现该问题:Strange behavior of Console.ReadKey() with multithreading

于 2013-03-06T09:00:23.877 回答