来自EventHandler的Console.Writeline

时间:2013-03-05 19:04:05

标签: c# windows console-application

我写了一个简单的异步TCP-Server - 效果很好。但是现在我想在Console-Testprogram上输出收到的数据。问题是,这不起作用!如果我将MainThread连接到EventHandler,程序什么都不做。 Debug显示调用了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
    }
}

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

1 个答案:

答案 0 :(得分:3)

你可能正在经历某种种族问题,虽然控制台应该免疫。请检查此问题,但请注意我无法重现此问题:Strange behaviour of Console.ReadKey() with multithreading