gpt4 book ai didi

c# - 异步编程问题

转载 作者:行者123 更新时间:2023-12-02 09:44:05 25 4
gpt4 key购买 nike

我最近发现了 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";
}
}
}

有什么想法吗?如果有人知道一些很好的教程和/或演示这些概念的视频,那就太棒了。

最佳答案

您正在调用异步方法,然后让您的应用程序完成。选项:

  • 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

就视频而言,我今年早些时候在 Progressive .NET 上举办了一次关于异步的 session - the video is online 。另外,我还有一些blog posts about async ,包括我的Eduasync系列。

此外,还有来自 Microsoft 团队的大量视频和博客文章。请参阅Async Home Page获取大量资源。

关于c# - 异步编程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8426390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com