I'm a complete newbie to C# and am writing a striped down serial port
class; but I'm confused as to whether I need to worry about the byte[] I
pass into WriteFile and ReadFile. I'm assuming that the IntPtr handle I
pass is safe. However I'm also thinking that since my application is
multithreaded, that while my worker thread is blocked waiting on a
FileRead, for example, that the CLR could initiate a GC while my UI
thread is running. Is that correct? If so, then I'm thinking that I
need to use lock, or some other mechanism, on the byte[] pointer that is
passed to both ReadFile and WriteFile. Assuming that's the case, is
there anything else I should be doing to make the code below reliable?
I've included parts of my C# code below.
Thanks much,
Rick Moll
---------------------------code sample start-----------------------
public class SerialPort
{
[DllImport("Kernel32.DLL")]
private static extern bool ReadFile(
IntPtr hFile,
byte[] lpBuffer,
int nNumberOfBytesToRead,
out int lpNumberOfBytesRead,
int lpOverlapped
);
[DllImport("Kernel32.DLL")]
private static extern bool WriteFile(
IntPtr hFile,
byte[] lpBuffer,
int nNumberOfBytesToWrite,
out int lpNumberOfBytesWritten,
int lpOverlapped
);
private const int INVALID_HANDLE_VALUE = -1;
public IntPtr handle = (IntPtr)INVALID_HANDLE_VALUE;
public bool Read( byte[] buffer,
out int numberOfBytesRead )
{
if (handle == (IntPtr)INVALID_HANDLE_VALUE) {
numberOfBytesRead = 0;
return false;
} else {
return ReadFile( handle,
buffer,
buffer.Length,
out numberOfBytesRead,
0 );
}
}
public bool Write( byte[] buffer,
out int numberOfBytesWritten )
{
if (handle == (IntPtr)INVALID_HANDLE_VALUE) {
numberOfBytesWritten = 0;
return false;
} else {
return WriteFile( handle,
buffer,
buffer.Length,
out numberOfBytesWritten,
0 );
}
}
}
---------------------------code sample end-----------------------