public static T GetFileLock<T>(
string fileName,
Func<string, T> lockFunction,
double secondsToWait = 5,
int retryMilliseconds = 200
)
Public Shared Function GetFileLock(Of T) (
fileName As String,
lockFunction As Func(Of String, T),
Optional secondsToWait As Double = 5,
Optional retryMilliseconds As Integer = 200
) As T
public:
generic<typename T>
static T GetFileLock(
String^ fileName,
Func<String^, T>^ lockFunction,
double secondsToWait = 5,
int retryMilliseconds = 200
)
The intent of this function is to provide a sane method for opening a file which may produce errors due to read/write contention. Usage of this class is fairly simple using the static methods built into the File class.
using (StreamReader reader = GetFileLock(File.OpenText))
{
// Read lines from the file
}
using (FileStream stream = GetFileLock(File.Create))
{
// Write bytes into the file
}
This method will only retry if an IOException occurs while executing the lockFunction. After retrying for at least secondsToWait seconds, this function will throw the last IOException it encountered.