UnauthorizedAccessException when accessing Virtual COM port
Hi,
My application opens a virtual COM port to access an USB device. (I'm using CDC ACM Port Driver by Thesycon GmbH).
My app opens the port and closes it correctly, if I disconnect the USB cable from the device before calling SerialPort.Close(), then the UnauthorizedAccessException is thrown. Notice that it's not the Close() that throws the exception. It's a separate thread (which is not created from my code) that throws it.
This is what the IDE's output window shows:
Code:
'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_32\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll'
'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\Microsoft.VisualStudio.HostingProcess.Utilities\9.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.HostingProcess.Utilities.dll'
'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Windows.Forms\2.0.0.0__b77a5c561934e089\System.Windows.Forms.dll'
'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System\2.0.0.0__b77a5c561934e089\System.dll'
'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Drawing\2.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll'
'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\Microsoft.VisualStudio.HostingProcess.Utilities.Sync\9.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.HostingProcess.Utilities.Sync.dll'
'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\9.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll'
'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\Temp\WindowsFormsApplication3\WindowsFormsApplication3\bin\Debug\WindowsFormsApplication3.vshost.exe'
'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Core\3.5.0.0__b77a5c561934e089\System.Core.dll'
'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Xml.Linq\3.5.0.0__b77a5c561934e089\System.Xml.Linq.dll'
'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Data.DataSetExtensions\3.5.0.0__b77a5c561934e089\System.Data.DataSetExtensions.dll'
'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_32\System.Data\2.0.0.0__b77a5c561934e089\System.Data.dll'
'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Deployment\2.0.0.0__b03f5f7f11d50a3a\System.Deployment.dll'
'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Xml\2.0.0.0__b77a5c561934e089\System.Xml.dll'
The thread 0xfb4 has exited with code 0 (0x0).
The thread 0xfbc has exited with code 0 (0x0).
'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\Temp\WindowsFormsApplication3\WindowsFormsApplication3\bin\Debug\WindowsFormsApplication3.exe', Symbols loaded.
>>>>> System.IO.Ports.SerialPort.Open() returned without any error
The thread 0xeec has exited with code 0 (0x0).
>>>>> System.IO.Ports.SerialPort.Close() returned without any error
The thread 0x814 has exited with code 0 (0x0).
The thread 0x888 has exited with code 0 (0x0).
A first chance exception of type 'System.UnauthorizedAccessException' occurred in System.dll
An unhandled exception of type 'System.UnauthorizedAccessException' occurred in System.dll
Additional information: Access to the port is denied.
The program '[0xF50] WindowsFormsApplication3.vshost.exe: Managed' has exited with code -532459699 (0xe0434f4d).
Is there a way to prevent this exception to be thrown?
Re: UnauthorizedAccessException when accessing Virtual COM port
Ive got the exact same problem. Its occuring in a Win32 component when SetCommMask is called (which runs Async and is where the exception is coming from) and then WaitCommEvent is called. I wrote a small Win32 serial port class in C++ that acts right on the Windows API and didnt called either the SetCommMask or the WaitCommEvent functions and when I called ReadFile to read data from the buffer it would throw an exception that I could catch.
I created a wrapper class for the C++ class in C# but I cannot get it to act reliably. My stack pointers and stuff keep getting moved because I am forced to use "unsafe" code.
I guess thats the only REAL way to get around it. As far as I can tell its a bug (a NASTY one albeit) in the .NET Framework.
Re: UnauthorizedAccessException when accessing Virtual COM port
I solved my problem adding a config file to my Visual Studio C# project. My app.config file is this:
Code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
<legacyUnhandledExceptionPolicy enabled="true"/>
</runtime>
</configuration>
as explained here:
http://connect.microsoft.com/VisualS...edbackID=98348
Re: UnauthorizedAccessException when accessing Virtual COM port
Or even better, I'd suggest trapping the exception (try/catch) and handling it. Microsoft (in the link posted by MontgomeryBurns) say that they thought it better to throw an exception to inform the client application that something was wrong - and I agree with them.
If I were writing an application using a USB port I'd want it to know if someone pulled the plug out half way through operation...
Also
Code:
My stack pointers and stuff keep getting moved because I am forced to use "unsafe" code.
You're never FORCED to use unsafe code. You can p/invoke using IntPtr-s and pin arrays manually using GCHandle.Alloc(..., GCHandleType.Pinned). If you're using asynchronous operation you should then handle the completed event to GCHandle.Free the pinned pointer once the asynchronous write has finished.
Darwen.
Re: UnauthorizedAccessException when accessing Virtual COM port
Quote:
Or even better, I'd suggest trapping the exception (try/catch) and handling it.
That's what I'd prefer, either. But you cannot trap the exception since it is thrown by a thread created somewhere else of my code. From the link:
Quote:
exception gets thrown on the event loop thread
Re: UnauthorizedAccessException when accessing Virtual COM port
What's the 'event loop thread' ?
If you want exceptions in a worker thread to be translated back to the thread which originally started the worker thread you have 2 options :
(1) Trap them yourself using try...catch and implement a mechanism to pass it back to the main thread.
(2) Use asynchronous delegates (i.e. BeginInvoke of a delegate). The exception is trapped by the framework on the thread that executes the delegate and automatically re-thrown in response to an EndInvoke on whichever thread EndInvoke is called on.
Darwen.
Re: UnauthorizedAccessException when accessing Virtual COM port
I mean that that exception is not thrown by my main thread nor any thread created from my code. I tried trapping it like this:
Code:
[STAThread]
static void Main(string[] argv)
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm(argv));
}
catch(Exception e)
{
MessageBox.Show(e.Message); // never goes here!
}
} // while debugging exception is thrown when pressing 'Debug Step' here
but the Exception is not trapped, because it is thrown later. While debugging, I press 'Step' when the cursor is on the last closing brace, only then the exception is thrown.
Quote:
What's the 'event loop thread' ?
I just quoted the text from the Microsoft answer in the microsoft connect website. I don't know exactly what he means, but I'm sure that the thread that throws the exception is not in my code (so I don't know how to trap it) because I identified it using the debugger in the 'Thread window'.
So how can I trap an exception thrown by other threads created by the Framework?
Re: UnauthorizedAccessException when accessing Virtual COM port
I ended up using some interop to catch this toughy. The thread that throws the exception is occurring in the function SetCommMask(HANDLE, DWORD) in kernel32.dll. This function spins off a separate thread to monitor the internal windows buffer where bytes are received from the port and it triggers WaitCommEvent and that is where your SerialPort.DataReceived event comes from.
Problem is it runs on a thread that is NOT part of user code (this is probably the "event loop thread" you noted earlier) so catching the exception through C# is virtually impossible without the app.config wrench noted by the OP. You either have to do that, or use some interop with the kernel32.dll to avoid calling the SetCommMask function and avoid creating that background thread that throws the exception. I did this, and called CreateFile(HANDLE, LPDCB), GetCommState(HANDLE, LPDCB), SetCommState(HANDLE, LPDCB), and ReadFile(HANDLE, void*, DWORD, LPDWORD, LPOVERLAPPED), and was able to read the port fine. Noted you will need to create a DCB struct to use this method. Either way is better than the exception bubbling up to the UI, crashing the CLR, and making doody all over your client.
From the MSDN regarding the SerialPort.DataReceived event
"The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke, which will do the work on the proper thread."
As far as I can tell, the only reason for the calls to SetCommMask and WaitCommEvent are for taking off a bit of CPU load and allowing the thread to block on WaitCommEvent until data is received on the internal buffer. So in other words, its not necessary for reading data from the buffer. Even if you call ReadFile and there is no data on the buffer, ReadFile will simply block until there IS data on the buffer.
As for my using unsafe code, no... I didnt have to use it, I had to use some interop and thats what I meant. My stack pointers were being moved and I totally forgot about the "fixed" keyword. But I used fixed and that "fixed" the problem, haha.
Re: UnauthorizedAccessException when accessing Virtual COM port
Quote:
Originally Posted by
MontgomeryBurns
I solved my problem adding a config file to my Visual Studio C# project. My app.config file is this:
Code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
<legacyUnhandledExceptionPolicy enabled="true"/>
</runtime>
</configuration>
as explained here:
http://connect.microsoft.com/VisualS...edbackID=98348
Thanks to everybody for sharing your knowledge. MontgomeryBurns's solution fixed my problem. I wrote a GUI for a USB device that creates a virtual serial port. The GUI can detect the presence of the device and connect or reconnect automatically multiple times, but would raise the aformentioned exception upon exit.
Re: UnauthorizedAccessException when accessing Virtual COM port
I have a similar problem:
My application connects to port, then I unplug the cable. Then I plug the cable again and reconnect to the port. Everything goes fine for a while (I can close and dispose SerialPort object after the unplug and can reconnect with the same object after replugging the cable. Even funnier I even can read port and write to it after replugging!) but after some time UnauthorizedAccessException saying "Access to the port is denied" is thrown.
I tried setting legacyUnhandledExceptionPolicy to true in the application configuration file but it didn't solve my problem.
Any suggestions?
Re: UnauthorizedAccessException when accessing Virtual COM port
Quote:
Originally Posted by
denizkartan
I have a similar problem:
My application connects to port, then I unplug the cable. Then I plug the cable again and reconnect to the port. Everything goes fine for a while (I can close and dispose SerialPort object after the unplug and can reconnect with the same object after replugging the cable. Even funnier I even can read port and write to it after replugging!) but after some time UnauthorizedAccessException saying "Access to the port is denied" is thrown.
I tried setting legacyUnhandledExceptionPolicy to true in the application configuration file but it didn't solve my problem.
Any suggestions?
Its an exception that's thrown from within the .NET Framework and you cant handle it and keep the application running. I fixed it by using some interop with the kernel32 library. Research how to open and read/write serial ports in Win32 C++ and then call the functions from C# code using some interop.
Re: UnauthorizedAccessException when accessing Virtual COM port
Hello,
I am running the .NET framework 3.5 and am having the same problem as all of you. I connect my USB cable to the PC and pull it while data is being transmitted. I have a try catch block that detects the dissapearrence of the COM port. When you reconnect it and restart the transmission I recieve the UnauthorizedAccessException. In the .NET framework 3.5 how do you prevent this or catch this one? I tried the config file but it did not work :(.
Any advice?
Re: UnauthorizedAccessException when accessing Virtual COM port
Better yet, one guy said use c++ to open the com ports. I know nothing about interops. Does this mean you can call a C++ class from C#?
Re: UnauthorizedAccessException when accessing Virtual COM port
Mr. burns' solution to add the config file to the project worked ! thank you.
Re: UnauthorizedAccessException when accessing Virtual COM port
maybe i was a little too hasty posting that last post ! ..
now the exception is thrown when my app exits....
Does anyone have a solution for this ?