0

I would like to write Async to 2 files some data, i've tried something like this:

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

The compiler error is:

The 'await' operator can only be used within an async method.

how to do it properly?

i would like also to do loop instruction with console.Write("X); as async

can someone help me ? i couldn't find some basic examples on google...

SharkyShark
  • 370
  • 1
  • 3
  • 15
  • 1
    The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task' – SharkyShark Aug 16 '17 at 10:53

1 Answers1

0

Try awaiting your result after the for loop:

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");
    }
}
senz
  • 879
  • 10
  • 25