后台工作程序在实例化时不启动

时间:2013-10-23 11:04:49

标签: c# backgroundworker

我有一个名为 ClientSocketService 的类,在实例化时创建后台线程并开始通过套接字侦听。

ClientSocketService.cs

public ClientSocketService(Socket sock) : this()
    {
        //Assign the Incomign socket to the Socket variable.
        _serviceSocket = sock;

        //Get and assing the network stream for the Socket.
        this._nStream = new NetworkStream(sock);

        //Initialize the Reciever Thread.
        RecieverThread = new BackgroundWorker();
        RecieverThread.DoWork += new DoWorkEventHandler(RecieverThread_StartListening);
        RecieverThread.RunWorkerAsync();
    }

我在另一个名为server的类中创建此类的Object,在创建类对象之后,另一个方法将该类添加到Collection并引发ClientAdded事件处理程序。

private void AcceptClientSocket(Socket sock)
    {            
        //Initialize new ClientSocketService.            
        ClientSocketService csservice = new ClientSocketService(sock);

        //Add the client to the List
        this.AddClientToList(csservice);
    }
    /// <summary>
    /// Adds the Client to the List.
    /// </summary>
    /// <param name="csservice"></param>
    private void AddClientToList(ClientSocketService csservice)
    {
        //Check for any abnormal Disconnections
        this.CheckAbnormalDC(csservice);
        //Ad the ClientSocketService to the List.
        this._clientsocketservices.Add(csservice);
        //Raise the Client Added Event Handler.
        this.OnClientAdded(new ClientSocketServiceEventArgs(csservice));
    }

我现在面临的问题是ClientSocketService类中的Background worker在调用所有Added事件处理程序事件后启动。

非常感谢任何帮助。

谢谢,

2 个答案:

答案 0 :(得分:0)

看起来你有几个线程正在运行,你需要在这些线程之间进行某种同步。例如:

  • MainThread
  • 线程1
  • 线程2

在这种情况下,即使您在Thread1之前启动Thread2,也无法保证线程按顺序执行工作。它可能会工作一次,但可能在其他时间不起作用。

有多个选项可用于同步线程,请查看

答案 1 :(得分:0)

我通过在clientsocketservice类中添加一个新的 ClientConnected 事件处理程序并订阅它来解决它。

现在,当调用ClientConnectedEventHandler时,我将ClientSocketService对象添加到List中。通过这种方式,我可以在将客户端添加到列表之前执行其他一些初始化/授权工作。

感谢所有人的帮助。