使用C#听文/事件流 [英] Listening to text/event-stream using C#

查看:233
本文介绍了使用C#听文/事件流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个C#类环绕一个简单的Web服务。 REST风格的东西很容易包裹起来,但现在我需要的东西时,在服务器上的变化。

I am writing a C# class to wrap around a simple web service. The RESTful stuff was easy to wrap up, but now I need to raise an event when something on the server changes.

我已经设置服务器最多可让事件引发一个事件。流可用,但我不知道如何拿起C#中的流

I've set the server up to make an event stream available, but I don't know how to pick up the stream in C#.

目前我洞是这样的:

public class ServiceWrapper
{
    private readonly wc = new WebClient();

    public ServiceWrapper()
    {
        wc.OpenReadAsync(new Uri(UriOfEvent));
        wc.OpenReadCompleted += ServerEventOccurs;
    }

    private void ServerEventOccurs(object sender, OpenReadCompletedEventArgs args)
    {
        using (var sr = new StreamReader(args.Result))
        {
            var message = ParseStream(sr);
            RaiseServerEventOccurred(message);
        }

        wc.OpenReadAsync(new Uri(UriOfEvent));
    } 

    //usual code for declaring and raising ServerEventOccurred event
}



}

//常规码

在我的测试中的事件会得到回升一次,但不是两次。在服务器上的事件本质上是一个开关 - 有事,它的推移,别的东西发生,它熄灭。我知道开关的作品,因为我已经迷上事件流达到一个正常的Web页面来测试它。

In my test the event gets picked up once, but not twice. The event on the server is essentially a switch - something happens and it goes on, something else happens and it goes off. I know the switching works, because I've hooked the event stream up to a normal web page to test it.

我应该如何处理事件在C#流?

How should I be dealing with event streams in C#?

编辑1:我已经更新了代码来解决TimVK指出错误,但事件流仍然没有被拾起第二次是应该的。

Edit 1: I've updated the code to fix the bug TimVK points out, but the event stream still isn't being picked up the second time it should be.

推荐答案

不,当你把你的厕所作为它的工作在创建始终在你的方法一个新的代替class属性?

Doesn't it work when you put your wc as a property in the class in stead of creating always a new one in your methods?

public class ServiceWrapper 
{ 
    WebClient wc {get;set;}
    public ServiceWrapper() 
    { 
        wc = new WebClient(); 
        wc.OpenReadAsync(new Uri(UriOfEvent)); 
        wc.OpenReadCompleted += ServerEventOccurs; 
    } 

    private void ServerEventOccurs(object sender, OpenReadCompletedEventArgs args) 
    { 
        using (var sr = new StreamReader(args.Result)) 
        { 
            var message = ParseStream(sr); 
            RaiseServerEventOccurred(message); 
        } 

        wc = new WebClient(); 
        wc.OpenReadAsync(new Uri(UriOfEvent)); 
    }  

    //usual code for declaring and raising ServerEventOccurred event 
} 



}

//常规码

然后我想事件应该每次提高。

Then I suppose the event should be raised everytime.

这篇关于使用C#听文/事件流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆