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();
}
}



0 comments:

我要啦免费统计