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!