I recently installed VS2012 and I'm reading on the new async modifier and how to use it for async programming.
Now, I'ts pretty easy to use with built-in framework function like in System.IO or in web service calls but I'm trying to use with my own function. I made a small console application, basically the async task is a random number that will be generated in loop until it equals 0 and I want to display loading message in the mean-time. Here's the code that I have done:
private static void Main(string[] args)
{
var rnd = new Random();
var factory = new TaskFactory();
var task = GetRandomNumber(rnd);
while(!task.IsCompleted){
System.Console.Write("Loading .");
System.Console.Write(".");
System.Console.Write("./n");
}
}
private static async Task GetRandomNumber(Random rnd)
{
await new Task(delegate
{
while (rnd.Next() != 0)
{
}
});
}
It's obvious that I'm pretty lost on how to do that here I just keep coding it like if I was multi, is it possible to implement this behavior with the async/await pattern? How?
async
does not necessarily imply "multithreaded". You can use Task.Run
to spin a new background task that you can await
.
private static void Main(string[] args)
{
var rnd = new Random();
var task = GetRandomNumber(rnd);
while(!task.IsCompleted){
System.Console.Write("Loading .");
System.Console.Write(".");
System.Console.Write("./n");
}
}
private static Task GetRandomNumber(Random rnd)
{
return Task.Run(() =>
{
while (rnd.Next() != 0)
{
}
});
}
Though I would probably do it like this:
private static void Main(string[] args)
{
MainAsync().Wait();
}
private static async Task MainAsync()
{
var rnd = new Random();
var randomTask = GetRandomNumber(rnd);
System.Console.Write("Loading .");
while (await Task.WhenAny(randomTask, Task.Delay(500)) != randomTask)
{
System.Console.Write(".");
}
System.Console.WriteLine();
}
private static Task GetRandomNumber(Random rnd)
{
return Task.Run(() =>
{
while (rnd.Next() != 0)
{
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.