none
如何结束一个由于 UdpClient.Receive() 而挂起的进程? RRS feed

  • 问题

  • 代码如下:

    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    
    namespace TestVisualCSharpConsole
    {
      class Program
      {
        class MyClass
        {
          private Thread myThread;
    
          public MyClass()
          {
            myThread = new Thread(new ThreadStart(func));
          }
    
          private void func()
          {
            UdpClient u = new UdpClient(4891);
            IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
    
            while (true)
            {
              u.Receive(ref remote);
            }
          }
    
          public void Start()
          {
            myThread.Start();
          }
    
          public void Stop()
          {
            myThread.Abort();  // 这个无效;
            myThread.Join();  // ...
            // 那么该怎么写?
          }
        }
    
        private static void Main()
        {
          MyClass myClass1 = new MyClass();
          myClass1.Start();
          Thread.Sleep(1000);
          myClass1.Stop();
        }
      }
    }
    

    MyClass.Stop() 方法该怎么写才能实现使进程 myThread 停止?


    EFanZh
    2010年6月17日 17:38

答案

  • udpClient.BeginReceive

    Stop的时候用udpClient.EndReceive



    The following is signature, not part of post
    Please mark the post answered your question as the answer, and mark other helpful posts as helpful, so they will appear differently to other users who are visiting your thread for the same problem.
    Visual C++ MVP
    • 已标记为答案 EFanZh 2010年6月26日 11:38
    2010年6月17日 19:38
    版主
  • 呃,用BeginReceive/EndReceive这样的异步方法就不用自己创建线程了……

    The following is signature, not part of post
    Please mark the post answered your question as the answer, and mark other helpful posts as helpful, so they will appear differently to other users who are visiting your thread for the same problem.
    Visual C++ MVP
    • 已标记为答案 EFanZh 2010年6月26日 11:38
    2010年6月23日 21:19
    版主

全部回复

  • udpClient.BeginReceive

    Stop的时候用udpClient.EndReceive



    The following is signature, not part of post
    Please mark the post answered your question as the answer, and mark other helpful posts as helpful, so they will appear differently to other users who are visiting your thread for the same problem.
    Visual C++ MVP
    • 已标记为答案 EFanZh 2010年6月26日 11:38
    2010年6月17日 19:38
    版主
  • 问题是,我在 Stop() 方法中是无法访问 u 的。

    而且,我想知道的是如果终结这个线程的执行或者不能从外界终结?


    EFanZh
    2010年6月18日 2:58
  • 呃,用BeginReceive/EndReceive这样的异步方法就不用自己创建线程了……

    The following is signature, not part of post
    Please mark the post answered your question as the answer, and mark other helpful posts as helpful, so they will appear differently to other users who are visiting your thread for the same problem.
    Visual C++ MVP
    • 已标记为答案 EFanZh 2010年6月26日 11:38
    2010年6月23日 21:19
    版主