Managing SerialPort Access Across Multiple Pages in Maui Blazor for Windows

Yusuf 791 Reputation points
2023-08-17T14:01:46.7733333+00:00

Hello,

I'm encountering an issue with my Maui Blazor application where I'm utilizing the SerialPort class to communicate with a COM port. The application works fine when I stay on the same page, but if I navigate to another page and then return, I get an "UnauthorizedAccessException" when trying to reopen the COM port.

Here's the relevant code from my Maui Blazor pages:

@page "/"

<p>@receivedData</p>


@code {
    private string receivedData = "";
    private System.IO.Ports.SerialPort serialPort;

    protected override void OnInitialized()
    {
        base.OnInitialized();
        serialPort = new System.IO.Ports.SerialPort("COM5", 9600);
        serialPort.DataReceived += SerialPort_DataReceived;
        serialPort.Open(); // System.UnauthorizedAccessException: 'Access to the path 'COM5' is denied.'
    }


    private void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        string data = serialPort.ReadLine();
        receivedData = data;
        InvokeAsync(() => StateHasChanged());
    }
}

In my scenario, I need to access SerialPort-related functionality across multiple Maui Blazor pages. How can I effectively manage the SerialPort instance when navigating between these pages? I suspect that the issue might be related to how the SerialPort is being handled during navigation.

I appreciate any insights or suggestions on how to resolve this problem while utilizing SerialPort functionality throughout various Maui Blazor pages.

Thank you for your assistance!

Developer technologies | .NET | Blazor
Developer technologies | .NET | .NET MAUI
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,766 Reputation points Volunteer Moderator
    2023-08-17T21:43:54.8866667+00:00

    you have two options:

    1. move the serialport code to a parent compoent, and the parent passes data to its children via property or callback
    2. change the serial port code to a service that is injected. the service should allow registering for events. then in OnInitialized() , the page should subscribe, on Dispose() it should unsubscribe()

  2. Yusuf 791 Reputation points
    2023-08-24T00:34:51.5566667+00:00

    I got some answers to my question, but I don’t know how to implement them and the problem is still not solved. I need some practical guidance or detailed steps to fix the issue that I’m facing. Some of the answers are too complicated or unclear for me to understand.

    Thank you in advance.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.