В этом example от Microsoft, метод имеет тип возвращаемого Task<int>
Почему некоторые методы требуют асинхронных возвращаемый тип задачи, а другие не
Пример 1:
async Task<int> AccessTheWebAsync()
{
// You need to add a reference to System.Net.Http to declare client.
HttpClient client = new HttpClient();
// GetStringAsync returns a Task<string>. That means that when you await the
// task you'll get a string (urlContents).
Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
// You can do work here that doesn't rely on the string from GetStringAsync.
DoIndependentWork();
// The await operator suspends AccessTheWebAsync.
// - AccessTheWebAsync can't continue until getStringTask is complete.
// - Meanwhile, control returns to the caller of AccessTheWebAsync.
// - Control resumes here when getStringTask is complete.
// - The await operator then retrieves the string result from getStringTask.
string urlContents = await getStringTask;
// The return statement specifies an integer result.
// Any methods that are awaiting AccessTheWebAsync retrieve the length value.
return urlContents.Length;
}
В этом второй пример, он использует async и ждет, НО не возвращает тип задачи <>, почему?
Пример 2:
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
ReadCharacters();
}
static async void ReadCharacters()
{
String result;
using (StreamReader reader = File.OpenText("existingfile.txt"))
{
Console.WriteLine("Opened file.");
result = await reader.ReadToEndAsync();
Console.WriteLine("Contains: " + result);
}
}
}
}
В-третьих, в первом примере, можно возвращать массив (строк)?
Итак, правильная практика всегда возвращает тип задачи <>? Как вы исправите пример выше? –
@Nexusfactor Правильная практика говорит, что возвращает «Задача», когда у вас нет фактического значения для возврата из метода, и используйте «Задача», когда у вас действительно есть значение для возврата из метода. –
MethodthatreturnsArrayAsync действительно будет ReadToEndAsync(), правильно? –