-3

I want to call the asynchronous reader method of TextReader, but always get a compile error:

var buffer = new char[10];

TextReader reader = new StreamReader(@"D:\temp\abc.txt");

// the following statement will get compile error
var readCount = await reader.ReadBlockAsync(buffer, 0, buffer.Length);

This is the error:

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'.

What is the right way to use ReadBlockAsync?

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
Redman
  • 642
  • 1
  • 5
  • 16
  • 5
    Have you considered marking this method with the 'async' modifier and changing its return type to 'Task'. – ta.speot.is Dec 02 '14 at 01:58
  • 1
    Seriously. I mean, it's hard to think of how much clearer the error message could be, not only in terms of what's wrong, but how to fix it! If you need more help than what the error message is already giving you, you need to explain that in specific detail. See http://stackoverflow.com/help/how-to-ask – Peter Duniho Dec 02 '14 at 02:03

1 Answers1

0

You simply need to mark the method with the async identifier as mentioned by others. The method then needs to return a Task, Task<T> or void. However void returning async methods are reserved for async event handlers. So in your case you'd probably want to return a Task<string>

public async Task<string> ReadAsync()
{
    var buffer = new char[10];

    TextReader reader = new StreamReader(@"D:\temp\abc.txt");

    var readCount = await reader.ReadBlockAsync(buffer, 0, buffer.Length);  

    return new string(buffer.Take(readCount).ToArray());
}

You may find the following resources useful: Best practices with Async/Await, Asynchronous Programming with Async-Await

NeddySpaghetti
  • 13,187
  • 5
  • 32
  • 61