I have an application that is doing a lot of USB I/O, and, much of that is logged. On some systems, I run into trouble where the logging function seems to take enough time I miss USB data. Not good. I tried to make a global folderitem and file, but that doesn’t appear to work. What are some of the ways I could make this more efficient?
Here’s the existing code:
[code] // Routine to Log to a window and a file if the checkbox for logging is enabled.
If gLoggingEnabled Then
Dim f As FolderItem = GetFolderItem(LOG_FILENAME)
Dim outputFile As TextOutputStream
If not f.exists then
Try
outputFile = TextOutputStream.Create(f)
Catch
MsgBox "Error creating log file."
End Try
Else
Try
outputFile = TextOutputStream.Append(f)
Catch
MsgBox "Error opening log file."
End Try
End If
Dim d as New Date
outputFile.WriteLine(Str(d.LongTime) + " " + s + Chr(13))
wnLog.list.Text = Str(d.LongTime) + " " + s + Chr(13) + wnLog.List.Text
wnLog.List.Refresh
outputFile.Close
The default code path needs to be very simple, e.g.:
// Routine to Log to a window and a file if the checkbox for logging is enabled.
If gLoggingEnabled Then
Static f As FolderItem
if f = Nil then f = GetFolderItem(LOG_FILENAME) // static so it only does this once
Static outputFile As TextOutputStream // static so it's only created once
if outputFIle = nil then
If not f.exists then
Try
outputFile = TextOutputStream.Create(f)
Catch
MsgBox "Error creating log file."
End Try
Else
Try
outputFile = TextOutputStream.Append(f)
Catch
MsgBox "Error opening log file."
End Try
End If
Dim d as New Date
outputFile.WriteLine(Str(d.LongTime) + " " + s + Chr(13))
// wnLog.list.Text = Str(d.LongTime) + " " + s + Chr(13) + wnLog.List.Text
// wnLog.List.Refresh
outputFile.Flush // writes the data to disk immediately, but leaves the file open
End If
Static variables are one-per-app.
You could also use Module properties which would provide similar function, or Class properties to allow the option of more than one log file if that was needed.
For updating the wnLog (which I assume is a window with a textfield) I would do that on a timer. Set the timer so it only fires every 60th of a second at most so it’s not always updating the screen.
why not make outputFile a static/global property?
Only open file if that’s nil.
If you get IOException, you can set it to nil and open it again next time.
If the file is on the USB stick, these peripherals are extremely slow, which may explain the issue.
I shall think Dave’s suggestion is the best, as it creates an extremely fast string buffer, then allows all time it needs to the writing process, which could be carried out in a thread or indeed during idle times if they exist.