Async-Await cant access to the serial port from another form? RRS feed

  • Question

  •  have stuck with async of the serial port and facing a really strange problem, I'm trying to send the file through the serial port asynchronously by 4096-byte chunks, the problem is that when I call -

    Await Task.Run(Sub()

    It gives me the exception of the serial port that serial port is closed, while it is opened. The funny thing if you do the same code in the main form, where serialport is located, the code works like a charm without any errors. But when I try to access the port from another form asynchronously it shows me an error about the port is closed. Is it any way to make it work?
     I am just curious why my code works in the form where the serial port located and doesn't in another form. Thanks in further
    Wednesday, February 5, 2020 7:52 PM

All replies

  • See if the code below will assist, it will compile but the serial port needs configuring. Also note that you can use this between forms and classes, forms and code modules etc.

    Imports System.IO.Ports
    Imports System.Runtime.CompilerServices
    Public Module SerialPortExtensions
        Public Async Function ReadAsync(SerialPort As SerialPort, buffer() As Byte, offset As Integer, count As Integer) As Task
            Dim BytesToRead = count
            Dim temp = New Byte(count - 1) {}
            Do While BytesToRead > 0
                Dim readBytes = Await SerialPort.BaseStream.ReadAsync(temp, 0, BytesToRead)
                Array.Copy(temp, 0, buffer, offset + count - BytesToRead, readBytes)
                BytesToRead -= readBytes
        End Function
        Public Async Function ReadAsync(SerialPort As SerialPort, Count As Integer) As Task(Of Byte())
            Dim buffer = New Byte(Count - 1) {}
            Await SerialPort.ReadAsync(buffer, 0, Count)
            Return buffer
        End Function
    End Module
    Public Module Demo
        Public Async Sub Example()
            ' configure as needed
            Dim sp As New SerialPort
            Dim results = Await sp.ReadAsync(8)
        End Sub
    End Module

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    profile for Karen Payne on Stack Exchange

    Wednesday, February 5, 2020 8:36 PM