【问题标题】:How to make the thread wait for specific seconds如何让线程等待特定秒
【发布时间】:2012-07-05 17:28:07
【问题描述】:

我有一个函数(请参阅下面的代码),它从网络上读取一些数据。这个函数的问题是有时它会很快返回,但有时它会无限期地等待。我听说线​​程可以帮助我等待一段确定的时间并返回。

您能否告诉我如何让线程等待“x”秒并在没有记录活动时返回。结果我的函数也返回一个字符串,是否可以在使用线程时捕获该值?

 private string ReadMessage(SslStream sslStream)
        {
            // Read the  message sent by the server.
            // The end of the message is signaled using the
            // "<EOF>" marker.
            byte[] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;

            try
            {
                bytes = sslStream.Read(buffer, 0, buffer.Length);

                // Use Decoder class to convert from bytes to UTF8
                // in case a character spans two buffers.
                Decoder decoder = Encoding.ASCII.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                messageData.Append(chars);
                // Check for EOF.
            }
            catch (Exception ex)
            {

                throw;
            }



            return messageData.ToString();
        }

对于安德烈·卡利尔的评论:

我需要读取/写入一些值到 SSL 服务器。对于每个写入操作,服务器都会发送一些响应,ReadMessage 负责读取传入的消息。我发现 ReadMessage(sslStream.Read(buffer, 0, buffer.Length);) 永远等待的情况。为了解决这个问题,我考虑了可以等待“x”秒然后返回的线程。以下代码演示了 ReadMEssage 的工作原理

 byte[] messsage = Encoding.UTF8.GetBytes(inputmsg);
            // Send hello message to the server. 
            sslStream.Write(messsage);
            sslStream.Flush();
            // Read message from the server.
            outputmsg = ReadMessage(sslStream);
           // Console.WriteLine("Server says: {0}", serverMessage);
            // Close the client connection.
            client.Close();

【问题讨论】:

  • logeeks,你可以调用 Thread.Sleep(x),其中 x 代表时间,以毫秒为单位。但是,这会暂停您的代码流。我想更好地了解您要实现的目标。您能否更好地解释一下您希望它的表现如何?
  • 谢谢,现在我明白你的意思了。您可以在单独的线程中运行响应,并在主线程中运行秒表,以了解何时中止另一个线程。但是,这将是矫枉过正。尝试@pstrjds 建议并设置读取超时。

标签: c# multithreading


【解决方案1】:

您不能(理智地)让第二个线程中断您正在执行此代码的线程。请改用read timeout

private string ReadMessage(SslStream sslStream)
{
    // set a timeout here or when creating the stream
    sslStream.ReadTimeout = 20*1000;
    // …
    try 
    {
        bytes = sslStream.Read(…);
    } 
    catch (IOException) 
    {
        // a timeout occurred, handle it
    }
}

顺便说一句,以下构造毫无意义:

try
{
    // some code
}
catch (Exception ex) {
    throw;
}

如果您所做的只是重新抛出,则根本不需要 try..catch 块。

【讨论】:

    【解决方案2】:

    您可以在SslStream 上设置ReadTimeout,以便对Read 的调用将在指定的时间后超时。

    【讨论】:

      【解决方案3】:

      如果您不想阻塞主线程,请使用异步模式

      在不确切知道您要实现什么目标的情况下,听起来您想从可能需要很长时间才能响应的 SSL 流中读取数据,而不会阻塞您的 UI/主线程。

      您可以考虑使用BeginRead 异步读取数据

      使用这种方法,您可以定义一个回调方法,每次 Read 读取数据并将其放入指定缓冲区时都会调用该方法。

      只是休眠(无论是使用Thread.Sleep 还是通过在SslStream 上设置ReadTimeout)都会阻塞运行此代码的线程。

      【讨论】:

        【解决方案4】:

        通过将 ReadMessage 放在自己的线程中等待答案,将其设计为异步的。提供答案后,创建一个事件返回到主代码以处理其输出。

        【讨论】:

          猜你喜欢
          • 2019-10-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-02
          • 2012-04-14
          相关资源
          最近更新 更多