我最近发现了CTP异步库,我想试着写一个玩具程序来熟悉新的概念,但是我遇到了一个问题。
我相信代码应该写成
Starting
stuff in the middle
task string但事实并非如此。下面是我运行的代码:
namespace TestingAsync
{
class Program
{
static void Main(string[] args)
{
AsyncTest a = new AsyncTest();
a.MethodAsync();
}
}
class AsyncTest
{
async public void MethodAsync()
{
Console.WriteLine("Starting");
string test = await Slow();
Console.WriteLine("stuff in the middle");
Console.WriteLine(test);
}
private async Task<string> Slow()
{
await TaskEx.Delay(5000);
return "task string";
}
}
}有什么想法吗?如果有人知道一些好的教程和/或视频来演示这些概念,那就太棒了。
发布于 2011-12-08 13:11:52
您正在调用一个异步方法,但随后只是让您的应用程序完成。选项:
Thread.Sleep (或Console.ReadLine)添加到Main方法,以便在后台线程发生异步事件时可以睡眠Task并等待Main方法返回。例如:
using System;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
AsyncTest a = new AsyncTest();
Task task = a.MethodAsync();
Console.WriteLine("Waiting in Main thread");
task.Wait();
}
}
class AsyncTest
{
public async Task MethodAsync()
{
Console.WriteLine("Starting");
string test = await Slow();
Console.WriteLine("stuff in the middle");
Console.WriteLine(test);
}
private async Task<string> Slow()
{
await TaskEx.Delay(5000);
return "task string";
}
}输出:
Starting
Waiting in Main thread
stuff in the middle
task string在视频方面,今年早些时候,我在渐进式.NET - the video is online上进行了一次异步会议。此外,我还有一些blog posts about async,包括我的Eduasync系列。
此外,还有来自微软团队的大量视频和博客文章。请参阅Async Home Page以获取大量资源。
发布于 2011-12-08 13:12:56
你的程序在5000毫秒之前就退出了。
https://stackoverflow.com/questions/8426390
复制相似问题