刚刚获得VS2012并试图获得处理async.
假设我有一个方法可以从阻塞源中获取一些值.我不希望方法的调用者阻止.我可以编写方法来获取在值到达时调用的回调,但由于我使用的是C#5,我决定使方法异步,因此调用者不必处理回调:
// contrived example (edited in response to Servy's comment)
public static Task<string> PromptForStringAsync(string prompt)
{
return Task.Factory.StartNew(() => {
Console.Write(prompt);
return Console.ReadLine();
});
}
Run Code Online (Sandbox Code Playgroud)
这是一个调用它的示例方法.如果PromptForStringAsync不是异步,则此方法需要在回调中嵌套回调.使用异步,我可以用这种非常自然的方式编写我的方法:
public static async Task GetNameAsync()
{
string firstname = await PromptForStringAsync("Enter your first name: ");
Console.WriteLine("Welcome {0}.", firstname);
string lastname = await PromptForStringAsync("Enter your last name: ");
Console.WriteLine("Name saved as '{0} {1}'.", firstname, lastname);
}
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.问题是当我调用 GetNameAsync时:
public static void DoStuff()
{
GetNameAsync();
MainWorkOfApplicationIDontWantBlocked();
}
Run Code Online (Sandbox Code Playgroud)
重点GetNameAsync是它是异步的.我不 …