我想将Async写入2个文件中的一些数据,我试过这样的事情:
private static void Main(string[] args)
{
FileStream file1 = File.Create(@"D:\test\plik1.dat");
FileStream file2 = File.Create(@"D:\test\plik2.dat");
var f1 = await write(file1);
var f2 = await write(file2);
for (int i = 0; i < 1024 * 1024; i++)
{
if (i % 100 == 0)
Console.Write("X");
}
}
private static async Task write(FileStream fs)
{
var zap = new StreamWriter(fs);
for (long i = 0; i < 1024 * 1024 * 250; i++)
{
zap.WriteAsync("xxx");
}
}
编译错误是:
等待&#39;运算符只能在异步方法中使用。
如何正确地做到这一点?
我还希望用console.Write("X);
作为async
答案 0 :(得分:0)
尝试在for循环后等待你的结果:
private static void Main(string[] args)
{
FileStream file1 = File.Create(@"D:\test\plik1.dat");
FileStream file2 = File.Create(@"D:\test\plik2.dat");
var f1 = Write(file1);
var f2 = Write(file2);
var work = DoWork();
Task.WaitAll(f1,f2,work);
}
private static async Task DoWork()
{
for (int i = 0; i < 1024 * 1024; i++)
{
if (i % 100 == 0)
Console.Write("X");
}
}
private static async Task Write(FileStream fs)
{
var zap = new StreamWriter(fs);
for (long i = 0; i < 1024 * 1024 * 250; i++)
{
await zap.WriteAsync("xxx");
}
}