简体   繁体   English

C#Windows服务事件

[英]C# Windows Service Events

So I am just messing around here nothing production just proof of concept with my first ever Windows Service. 因此,我只是在这里弄乱了我的第一个Windows服务,没有任何产品只是概念的证明。

I am trying to essentially create a windows service that sits as the listener for a signalr connection. 我试图从本质上创建一个Windows服务,该服务充当信号器连接的侦听器。 In essence, I will have a windows application and a windows service. 本质上,我将拥有Windows应用程序和Windows服务。 The win service will handle connecting to the signalr hub and on signalr calls fire an event. Win服务将处理连接到Signalr集线器的操作,并在Signalr呼叫时触发事件。 The windows application will listen for these events and perform actions based on them. Windows应用程序将侦听这些事件并根据它们执行操作。

Currently I cannot get this to work. 目前,我无法使它正常工作。 I have never worked with events, or windows services before. 我以前从未使用过事件或Windows服务。 In my windows application my events never hit their break points, as well I log an error of null reference exception from the 在我的Windows应用程序中,我的事件从未达到过断点,而且我记录了来自

ConnectToHub() ConnectToHub()

Alright if I comment out the OnConnected() method call I log a successful connection to the hub. 好吧,如果我注释掉OnConnected()方法调用,则会记录到集线器的成功连接。 I have never worked with events before so is my mistake with the events? 我以前从未参与过活动,所以我在活动中犯错了吗?

I debated that this approach was a bit overkill. 我争论说这种方法有点过大。 However, for me it was a proof of concept that I could find a use for a long running windows service, and adding some events into the mix. 但是,对我来说,这是一个概念证明,可以找到长期运行的Windows服务的用途,并向其中添加一些事件。

Code for service: 服务代码:

public delegate void MessageRecievedEventHanlder(object sender, MessageRecievedArgs e);
public delegate void ConnectedToHubEventHandler(object sender, ConnectedArgs e);
public partial class SignalRService : ServiceBase
{

    IHubProxy _hub;
    HubConnection connection;
    string url = @"http://localhost:8080/";
    private Message LastMessage;
    public static event MessageRecievedEventHanlder NewMessage;

    protected virtual void OnNewMessage(MessageRecievedArgs e)
    {
        NewMessage(null, e);
    }

    public static event ConnectedToHubEventHandler Connected;

    protected virtual void OnConnected(ConnectedArgs e) {
        System.IO.File.WriteAllText(@"C:\Users\Bailey Miller\Desktop\FTP\Logg.txt", "Hit OnConnected " + e.Success +" " + Connected != null ? "Isn't null" : "Null event");
        Connected(null, e);

    }

    public SignalRService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        ConnectToHub().Wait();

    }

    private async Task ConnectToHub()
    {
        try
        {
            //Connecting

            if (connection == null)
            {
                connection = new HubConnection(url);
            }
            if (_hub == null)
            {
                _hub = connection.CreateHubProxy("ChatHub");
            }

            await connection.Start();

            //Connected

            //Configure all the incoming options
            _hub.On<Message>("RecieveMessage", IncomingMessage);
            System.IO.File.WriteAllText(@"C:\Users\Bailey Miller\Desktop\FTP\Succes.txt", "Connected");
            OnConnected(new ConnectedArgs(true));

        }
        catch (Exception ex)
        {
            //Failed
            //OnConnected(new ConnectedArgs(false));
            System.IO.File.WriteAllText(@"C:\Users\Bailey Miller\Desktop\FTP\Fail.txt", "Failed to connect " + ex.Message.ToString());
        }

    }

    private void IncomingMessage(Message state)
    {
        DateTime? lmt;
        //Determine if has lastmessagetime
        if (LastMessage == null) {
            lmt = null;
        }
        else {
            lmt = LastMessage.RecievedAt;
        }

        LastMessage = state;

        //New Message
        //OnNewMessage(new MessageRecievedArgs(state, lmt));
    }

    protected override void OnStop()
    {
    }
}

public class MessageRecievedArgs : EventArgs
{
    public Message NewMessage { get; }
    public DateTime? LastMessageTime { get; }

    public MessageRecievedArgs(Message msg, DateTime? lmt) {
        this.NewMessage = msg;
        this.LastMessageTime = lmt;
    }
}

public class ConnectedArgs : EventArgs {
    public bool Success { get; }

    public ConnectedArgs(bool suc) {
        this.Success = suc;
    }
}

My windows application as of now: 到目前为止,我的Windows应用程序:

public MainWindow()
    {
        InitializeComponent();
        SignalRService.SignalRService.NewMessage += SignalRService_NewMessage;
        SignalRService.SignalRService.Connected += SignalRService_Connected;
    }

    private void SignalRService_Connected(object sender, SignalRService.ConnectedArgs e)
    {
        throw new NotImplementedException();
    }

    private void SignalRService_NewMessage(object sender, SignalRService.MessageRecievedArgs e)
    {
        throw new NotImplementedException();
    }

Your question is a bit broad- you don't describe exactly what isn't working, so I am guessing that when you start your service, it says "starting..." for a long while and eventually windows service manager gives you an error saying your service didn't start in a timely fashion. 您的问题有点笼统-您没有确切描述什么不起作用,所以我猜想当您启动服务时,它会说“正在启动...”很长时间,最终Windows服务管理器会为您提供错误提示您的服务未及时启动。 The issue is that OnStart() is expected to return- you can't block the thread there with the Wait() call. 问题是OnStart()应该返回-您不能通过Wait()调用在那里阻塞线程。 My suggestion would be to spawn a new background thread here to perform the waiting, then exit. 我的建议是在此处生成一个新的后台线程以执行等待,然后退出。 That should get you past the first hurdle. 那应该使您摆脱第一个障碍。

As another aside... You can add a regular main method to a windows service project, change the project type to Console Application, and run it that way to reduce your debugging cycle time. 另外...您可以向Windows服务项目中添加常规的main方法,将项目类型更改为Console Application,然后以这种方式运行它以减少调试周期。 Then when you are sure it basically works, change the project type back to Windows Service and install it. 然后,在确定它基本可以正常工作时,将项目类型更改回Windows Service并安装它。

EDIT: Now that you have a better error description, I see the real problem. 编辑:现在您有更好的错误描述,我看到了真正的问题。 The issue is that you are raising an event without checking for null first. 问题是您在引发事件时未先检查null。 Event fields are null until you attach a listener. 在附加侦听器之前,事件字段为null。 So change your code as follows: 因此,如下更改代码:

protected virtual void OnConnected(ConnectedArgs e) {
    System.IO.File.WriteAllText(@"C:\Users\Bailey Miller\Desktop\FTP\Logg.txt", "Hit OnConnected " + e.Success +" " + Connected != null ? "Isn't null" : "Null event");

    ConnectedToHubEventHandler connectedEvent = Connected;
    if (connectedEvent != null) // This event might be null, so check first
        connectedEvent(null, e);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM