2012-02-07 127 views
1

我在写一个C#程序,它一次运行两个IRC连接。 的连接线程,每个线程开始像这样:C#使线程等待定时器

MainThread = new Thread(new ThreadStart(StartMainProcessor)); 
      MainThread.IsBackground = false; 
      MainThread.Start(); 

private void StartMainProcessor() { 
      MainProcessor.Bot.Connect(); 
      //while (true) { } 
     } 

Bot.Connect()看起来像这样(有点删节版):

public void Connect() { 
      try { 
       Client.Connect(IRCHelper.SERVER, IRCHelper.PORT); 
      } 
      catch (CouldNotConnectException e) { 
       Reconnect(true); 
       return; 
      } 

      try { 
       Client.Listen(); 
      } 
      catch (Exception e) { 
       Reconnect(false); 
       return; 
      } 
     } 

这工作得很好,直到机器人断开连接(这总是会最终发生,这是IRC的本质)。 当它断开连接时,将调用Reconnect(),启动一个计时器。当该计时器到期时,僵尸意味着再次调用Connect()。计时器的原因是IRC服务器有时会拒绝立即重新连接。

但是,一旦Connect()方法结束,线程结束,程序(控制台应用程序)退出。 (Client.Listen()被阻塞)

我以前通过在StartMainProcessor()中添加while(true){}来克服了这个问题...但是这样吃了100%的CPU,我真的更喜欢不同的解。

谢谢你的帮助。 :)

+0

是否必须重新连接是由与previosu连接相同的线程进行的? – 2012-02-07 10:52:43

回答

2

听起来像你需要一个信号结构。例如,您可以使用类似AutoResetEvent的东西来阻止线程调用重新连接,即调用重新连接,启动计时器,然后阻止线程。然后在timer expired事件处理程序中设置自动重置事件,以允许线程继续(取消阻止)并调用Connect。

我不喜欢旋转处理器 - 当您添加无限循环或sleeps in loops浪费大量的CPU资源。

1

为什么你不只是Thread.Sleep里面Bot.Reconnect?这会使线程保持活动状态,并在准备再次拨打Bot.Connect时将其唤醒。

+0

+1睡眠/连接/侦听回路是显而易见的解决方案。可能不被OP使用,因为所有的帖子都说sleep()是反模式,必须使用定时器:(( – 2012-02-07 10:28:54

+0

我想这样做更有意义,我确实有Thread.Sleep()是的,我猜我应该听听互联网,哈哈:)谢谢,达人 – Xenoprimate 2012-02-07 10:36:28

+0

@MartinJames,'Thread.Sleep' ** IS **反模式...它是相对无害的,但它仍然是一个反-pattern。 – Kiril 2012-02-07 16:01:13

0

你可能想尝试类似的东西

private bool canExitThread; 
private void StartMainProcessor() 
{ 
    while (canExitThread) 
    { 
     //do the magic here 
     System.Threading.Thread.Sleep(1); //make sure you allow thread to do the job, otherwise you will get 100 cpu usage 

     //do the connecting, disconnecting, listening 
    } 
} 

你也可以检查,如果客户端连接?如果是这样,那么你应该检查在主循环内,如果它断开连接 - 调用connect方法。

希望能给你一个想法如何去做。

也看看下面的文章,这可能会解释一些更多的东西。 http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx

+0

Icky!不要这样做......他可以阻止输入,信号灯或手动重置事件,告诉他什么时候退出。 – Kiril 2012-02-07 16:04:06

0

如何对这样的事情

using System; 
using System.Diagnostics; 
using System.Threading; 
using System.Threading.Tasks; 

namespace Server 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.WriteLine("Starting server.."); 

      foreach (var connection in new[] {new Connection(TimeSpan.FromSeconds(1)), new Connection(TimeSpan.FromSeconds(1))}) 
       ThreadPool.QueueUserWorkItem(connection.Connect); 

      Console.WriteLine("Server running. Press Enter to quit."); 

      Console.ReadLine(); 
     } 
    } 

    public class Connection //might be good to implement IDisposable and disconnect on Dipose() 
    { 
     private readonly TimeSpan _reConnectionPause; 

     public Connection(TimeSpan reConnectionPause) 
     { 
      _reConnectionPause = reConnectionPause; 
     } 

     //You probably need a Disconnect too 
     public void Connect(object state) 
     { 
      try 
      { 
       //for testing assume connection success Client.Connect(IRCHelper.SERVER, IRCHelper.PORT); 
       Debug.WriteLine("Open Connection"); 
      } 
      catch (Exception) 
      { 
       //You might want a retry limit here 
       Connect(state); 
      } 

      try 
      { 
       //Client.Listen(); 
       //Simulate sesison lifetime 
       Thread.Sleep(1000); 
       throw new Exception(); 
      } 
      catch (Exception) 
      { 
       Debug.WriteLine("Session end"); 
       Thread.Sleep(_reConnectionPause); 
       Connect(state); 
      } 
     } 
    } 
} 
0

我相信你有Main方法,所以我们为什么不从那里开始:

private static readonly MAX_NUM_BOTS = 2; 

static void Main(string[] args) 
{ 
    List<Thread> ircBotThreads = new List<Thread>(); 
    for(int numBots = 0; numBots < MAX_NUM_BOTS; numButs++) 
    { 
     Thread t = new Thread(()=>{StartMainProcessor();}); 
     t.IsBackground = false; 
     t.Start(); 
     ircBotThreads.Add(t); 
    } 

    // Block until all of your threads are done 
    foreach(Thread t in ircBotThreads) 
    { 
     t.Join(); 
    } 

    Console.WriteLine("Goodbye!"); 
} 

private static void StartMainProcessor() 
{ 
    MainProcessor.Bot.Connect(); 
} 

然后,你可以这样做:

// 30 second time out (or whatever you want) 
private static readonly TimeSpan TIMEOUT = TimeSpan.FromSeconds(30.0); 

// specify the maximum number of connection attempts 
private static readonly int MAX_RECONNECTS = 10; 

public void Connect() 
{ 
    bool shouldListen = false; 
    // This is your connect and re-connect loop 
    for(int i = 0; i < MAX_RECONNECTS; i++) 
    { 
     try 
     { 
      Client.Connect(IRCHelper.SERVER, IRCHelper.PORT); 
      shouldListen = true; 
     } 
     catch (CouldNotConnectException e) 
     { 
      // It's OK to sleep here, because you know exactly 
      // how long you need to wait before you try and 
      // reconnect 
      Thread.Sleep((long)TIMEOUT.TotalMilliseconds); 
      shouldListen = false; 
     } 
    } 

    while(shouldListen) 
    { 
     try 
     { 
      Client.Listen(); 
     } 
     catch (Exception e) 
     { 
      // Handle the exception 
     } 
    } 
} 

这是一个非常粗糙的d筏,但其概念是,你一直试图重新连接,直到你失败。一旦你连接了,你就可以听(我假定你在IRC中听一些东西),并处理这些数据,直到你决定不再需要做这项工作。