Thursday, July 24, 2008

c# Asynchronous read write file

Quite often, you need to perform IO in .Net.
It is very useful that when coding windows form application, you perform asynchronous actions. Nobody like a freezing UI.
http://www.devsource.com/c/a/Using-VS/Making-Asynchronous-File-IO-Work-in-NET-A-Survival-Guide/



static void asyncWrite()
{
byte[] data = new byte[BUFFER_SIZE];
FileStream fs = new FileStream("writetest.dat", FileMode.Create,
FileAccess.Write, FileShare.None, 1, true);
try
{
// initiate an asynchronous write
Console.WriteLine("start write");
IAsyncResult ar = fs.BeginWrite(data, 0,
data.Length, null, null);
if (ar.CompletedSynchronously)
{
Console.WriteLine("Operation completed synchronously.");
}
else
{
// write is proceeding in the background.
// wait for the operation to complete
while (!ar.IsCompleted)
{
Console.Write('.');
System.Threading.Thread.Sleep(10);
}
Console.WriteLine();
}
// harvest the result
fs.EndWrite(ar);
Console.WriteLine("data written");
}
finally
{
fs.Close();
}
}



1 comment:

Anonymous said...

The code that you have posted will not write asynchronusly, that is unless it is overwriting an exisitng file on disk. If you had read the article that you lifted the code from, you would have realized that. In order to do Asynchronus writes, you have to create a delegate and call the beginInvoke function.