There is an external library which has a function that returns a value with a certain delay (sleep for 200-1000ms), C++ code:
__declspec( dllexport )
char ReadNextChar()
{
char OneChar[2];
while (Receive((char*)&OneChar)==-1) {Sleep(200);}
return OneChar[0];
}
In the main program running thread,
C# code:
public void Start()
{
thread = new Thread(ReadChar);
thread.IsBackground = true;
thread.Priority = ThreadPriority.BelowNormal;
thread.Start()
}
char currentChar;
[DllImport("reader.dll")]
public extern char ReadNextChar();
private void ReadChar()
{
while(true) {
currentChar=ReadNextChar();
}
}
It seems to me that this can be seriously optimised. What is the best way to do this task? (how does it really work while external function sleep?). Thanks.
The typical way to do this on win32 would be to use an event and signal this event from the ReadNextChar function.
This is how the Win32 ReadFile function works when using overlapped mode (http://msdn.microsoft.com/en-us/library/aa365467(v=vs.85).aspx)
You can then use WaitForSingleObject to put the thread to sleep. It will become runnable again when the event is signalled.
This would make your implementation more complicated and would additionally require modifications to the dll. Now, it is only really worth doing this if the read you are doing can actually be waited on – otherwise you will end up having to add another thread in your dll that polls and sets the event (not much point in doing this if you are doing this for optimization purposes as it will be a pessimistic optimization, to say the least).
To be honest, since you are likely to be sleeping for at least 200ms, polling your read function is unlikely to cause any significant performance issues – don’t optimize it for the sake of it.
Clearly something that your code does not do is to make the thread exit-able without terminate()ing it. I would personally put the sleep in the c# code and return a read success code from the ReadNextChar function without spinning in a loop or having any sleeps in there. I expect your code is just an example though..