I am using this code to write asynchronously to a file
public static void AsyncWrite(string file, string text)
{
try
{
byte[] data = Encoding.Unicode.GetBytes(text);
using ( FileStream fs = new FileStream(file, FileMode.Create,
FileAccess.Write, FileShare.Read, 1, true))
fs.BeginWrite(data, 0, data.Length, null, null);
}
catch
{
}
}
For some reason, from time to time, rather than writing text into the file as expected, Notepad++ shows the following ouput :

BeginWriteis asynchronous, so it might well happen that the stream is closed through theusingstatement while other things are happening.I’d not use
usingwhen doing asynchronous writing. Instead I’d create a proper callback method and close the stream there. This would also give you the chance to callEndWriteas recommended.