日期:2014-05-17 浏览次数:20918 次
private void Form1_Load(object sender, EventArgs e)
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
const int SIZE = 10; //方便测试这里设置小一点
var input = "AWfs测试_fs2测试AS测试34再测试一下;&)$@Lrwer{DWUEND.";
var buffer = new byte[SIZE];
var chars = Encoding.UTF8.GetChars(buffer); //其实是Size的一半,C#中一个字符占两字节
//AsyncCallback callBack = args =>
//{
// //弄了个listBox反馈结果
// if (this.listBox1.InvokeRequired)
// this.listBox1.Invoke(new Action(() => this.listBox1.Items.Add(string.Format("\r\nHad written file: {0}.txt", (int)args.AsyncState))));
//};
sw.Start();
using (var sr = new System.IO.StringReader(input))
{
int offset = 0, times = 0;
IAsyncResult asyResult = null;
while (times < 10 && sr.Peek() > -1)
{
//读到的字符数量,上面忽略了它,在最后一个文件会有bug
offset = sr.Read(chars, 0, chars.Length);
buffer = Encoding.UTF8.GetBytes(chars, 0, offset);
using (var fs = new FileStream(Application.StartupPath + "\\" + ++times + ".txt", FileMode.Create))
{
//异步写数据,无回调
//asyResult = fs.BeginWrite(buffer, 0, offset, callBack, times);
asyResult = fs.BeginWrite(buffer, 0, buffer.Length, null, null);
fs.EndWrite(asyResult);
fs.Flush();
fs.Close();
}
}
}
sw.Stop();
this.label1.Text = sw.ElapsedTicks.ToString();
//上面那个用了回调是2001392 左右,去掉后38563,提升很多
}