I'm sending command file in one folder and receive answer file in another folder.
My print method need to return number of fiscal invoice which is generated by printer and can be found in answer file.
So my method look like this
public int PrintInvoice()
{
//Do some code of sending command file
//Wait until answer file received
while(!_answerFileReceived){}
//Process answer file and return Invoice number
}Also I have FileSystemWatcher which monitor answer directory (file creation) with code
fswWatcher_FileCreated(object sender, FileSystemEventArgs e)
{
_answerFileReceived = true;
}My question is "Is this safe" and can I have exceptions, or do you have any suggestion of another approach to above problem.
Thank you.
VulpesPosted Oct 17, 2011, 10:41 AM
As an alternative to using the UI thread (if that's what you're doing), you could use a BackgroundWorker to do the operation which would keep the UI responsive. However, you'd still have the 'time out' problem even then.
Sam HobbsPosted Oct 18, 2011, 2:22 AM
Midhat AdemovicPosted Oct 18, 2011, 2:01 AM
I changed my approach based on your suggestions. I totaly loose FileSystemWatcher and put the monitor logic inside PrintMethod like
bool fileArived = false;
//Code for monitor answer file
for(int i = 1; i < 250; i++)
{
//Wait 20 ms for answer (max 5 sec)
Thread.Sleep(20);
//Is answer file received
if(File.Exists("AnsferFile.txt"))
{
fileArevied = true;
break;
}
}if(fileArevied)
{
//process file and get Invoice number
}else
{
//Error handling
}This way there is not infinite loops and everything is in one place.
Sam HobbsPosted Oct 17, 2011, 7:11 PM
VulpesPosted Oct 17, 2011, 6:51 PM
Sam HobbsPosted Oct 17, 2011, 5:28 PM
If not, then I would look for samples using the third party software that you are using. Are there no samples?
I don't know how those printers work so I don't understand about answer files so since you already have an answer, I probably cannot help. I however don't understand why you miust do both; wait for an answer file and monitor the directory.
I would expect the third party software to have an asynchronous way to send data that would include a timeout, and then most of what you are doing here would be unnecessary. I sure don't understand the need to use Sleep and DoEvents. It seems to me that the combination of FileSystemWatcher (for success) and the timer (for failure) would be sufficient. But if it works, then that is good.