【问题标题】:stdin is corrupt when reading it from non UI thread从非 UI 线程读取 stdin 时已损坏
【发布时间】:2015-08-14 20:49:29
【问题描述】:

我正在尝试使用 Google NativeMessaging 接收来自 Chrome 的消息,我的 WinForms 应用程序通过每 0.1 秒调用以下函数来读取从我在 Chrome 中的扩展程序发送的消息:

Public Function read_message() As String
        'Read in first 4 bytes for length...
        Dim stdin As Stream = Console.OpenStandardInput()

        Dim bytelen(LENGTH_BYTE_COUNT - 1) As Byte
        stdin.Read(bytelen, 0, LENGTH_BYTE_COUNT)

        Dim msglen As Integer = BitConverter.ToInt32(bytelen, 0)

        'Read the message
        Dim msg As String = ""
        For i As Integer = 0 To msglen - 1
            msg &= ChrW(stdin.ReadByte())
        Next i

        stdin.Close()
        stdin.Dispose()

        Return msg
    End Function

在我上面解释的场景中一切正常,但是,我希望这个函数在不同的线程中重复运行。

因此,当我创建新线程时,它具有相似的计时器和相似的间隔,结果变得一团糟,来自 Chrome 的短信重叠,一些消息被简单地遗漏,有时返回损坏的消息,我无法理解为什么这在 UI 线程中完美运行,而在不同的线程中给出奇怪的结果,即使我放松阅读时间间隔,有什么线索吗?

附言

作为一个附带问题,鉴于我必须使用 Winforms,我实际上不确定使用计时器从标准输入读取消息是最好的方法,有没有更好的方法来检测消息何时“到达”到标准输入流?

【问题讨论】:

    标签: vb.net multithreading winforms stdin chrome-native-messaging


    【解决方案1】:

    在这里找到解决方案:Very Slow to pass “large” amount of data from Chrome Extension to Host (written in C#)

    问题是stdin.ReadByte运行很慢,应该换成StreamReader(stdin)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      • 2020-06-02
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      相关资源
      最近更新 更多