I implemented an azure function where in every request I read the contents from a local file (about 100 bytes) and I return the response. I read diffrent parts of the file depending on query string (fromPosition
).
public class Reader
{
public static byte[] GetData(int fromPosition)
{
using(var fileStream = File.OpenRead("myLocalFilePath"))
{
byte[] data = new byte[100];
fileStream.Position = fromPosition;
fileStream.Read(data, 0, 100);
return data;
}
}
}
The problem with this code is that it takes about 1 sec to open the file and to return the data in every request.
I modified the code to keep always the file open (removed using
statement, the static FileStream
is opened once and not disposed), used also lock
to protect from multiple requests.
public class Reader
{
static object locker = new object();
static FileStream fileStream;
public static byte[] GetData(int fromPosition)
{
lock(locker)
{
if(fileStream == null)
fileStream = File.OpenRead("myLocalFilePath");
byte[] data = new byte[100];
fileStream.Position = fromPosition;
fileStream.Read(data, 0, 100);
return data;
}
}
}
This code takes about 1 sec in the first request, but in all next requests it returns immediately (0 milliseconds). So I have a massive improvement in speed, my azure function now completes quickly, I suppose this is also good for the cost.
Is there any downside of keeping the FileStream handle (just one handle) always open regarding the azure cost?