Javascript";EventSource“;在C#.NET 5.0中

Javascript";EventSource“;在C#.NET 5.0中,javascript,c#,wpf,.net-5,eventsource,Javascript,C#,Wpf,.net 5,Eventsource,我的公司选择“Mercure”()来管理服务器发送的事件。 我们在服务器上安装“Mercure HUB”,现在,在C#.NET 5.0中,我必须实现服务器端(发布服务器,我已经实现了)和客户端(订阅服务器)。 订阅服务器必须使用WPF完成 在“入门”页面中,我可以看到一个需要转换为C的Javascript示例# 我不知道如何在C中管理“EventSource”# 有什么想法吗 // The subscriber subscribes to updates for the https://exam

我的公司选择“Mercure”()来管理服务器发送的事件。 我们在服务器上安装“Mercure HUB”,现在,在C#.NET 5.0中,我必须实现服务器端(发布服务器,我已经实现了)和客户端(订阅服务器)。 订阅服务器必须使用WPF完成

在“入门”页面中,我可以看到一个需要转换为C的Javascript示例# 我不知道如何在C中管理“EventSource”# 有什么想法吗

// The subscriber subscribes to updates for the https://example.com/users/dunglas topic
// and to any topic matching https://example.com/books/{id}
const url = new URL('https://localhost/.well-known/mercure');
url.searchParams.append('topic', 'https://example.com/books/{id}');
url.searchParams.append('topic', 'https://example.com/users/dunglas');
// The URL class is a convenient way to generate URLs such as https://localhost/.well-known/mercure?topic=https://example.com/books/{id}&topic=https://example.com/users/dunglas
const eventSource = new EventSource(url);
// The callback will be called every time an update is published
eventSource.onmessage = e => console.log(e); // do something with the payload

此页面的代码有效()


你是说你想让C#客户端而不是浏览器客户端监听事件?还是因为你在用Blazor?还是怎样你的解释缺乏背景,也不清楚你自己在这方面付出了什么努力。e、 看起来很有趣。你搜索了什么吗?谢谢,我在原始帖子中添加了一些信息。我做了一些研究,尝试使用GetAsync订阅一些活动,现在我尝试了你的建议,但没有任何效果。当我进行这个异步调用时,似乎WPF页面被困在调用的循环中,我不能做任何其他事情,所以这是WPF…这对我们有点帮助。但是您需要向我们展示您尝试过的代码,这样我们才能了解问题所在。例如,您可能需要将侦听事件的工作转移到后台工作任务。我的错,我管理了一个新线程,现在您的建议起作用了!非常感谢,没问题。如果您解决了这个问题,请在下面添加您的代码解决方案,并进行简要说明,以利于其他人(也为了您的利益,如果它吸引了投票)-谢谢。当问题附有答案时,这个网站更有用!
static async Task Main(string[] args)
{
    HttpClient client = new HttpClient();
    client.Timeout = TimeSpan.FromSeconds(5);
    string stockSymbol = "VTSAX";
    string url = $"http://localhost:9000/stockpriceupdates/{stockSymbol}";

    while (true)
    {
        try
        {
            Console.WriteLine("Establishing connection");
            using (var streamReader = new StreamReader(await client.GetStreamAsync(url)))
            {
                while (!streamReader.EndOfStream)
                {
                    var message = await streamReader.ReadLineAsync();
                    Console.WriteLine($"Received price update: {message}");
                }
            }
        }
        catch(Exception ex)
        {
            //Here you can check for 
            //specific types of errors before continuing
            //Since this is a simple example, i'm always going to retry
            Console.WriteLine($"Error: {ex.Message}");
            Console.WriteLine("Retrying in 5 seconds");
            await Task.Delay(TimeSpan.FromSeconds(5));
        }
    }
}