4

因此,我一直在尝试创建一些代码,在 while 循环上发送数据,特别是通过 UdpClient 将活动数据包发送到服务器。

 static void doSend(string ip, int port)
    {
        while (isSending)
        {
            _sockMain = new UdpClient(ip, port);
            // Code for datagram here, took it out
            _sockMain.Send(arr_bData, arr_bData.Length);
        }
    }

但是当我调用“停止”方法时,它会陷入一个不断循环并且不会出来。如何将while循环放入线程?所以我可以在停止时中止线程,取消循环?

4

4 回答 4

9

它挂起是因为您的 doSend 方法适用于 UI 线程。您可以使用类似下面的类使其在单独的线程上运行,或者您可以使用BackgroundWorkerClass

public class DataSender
    {
        public DataSender(string ip, int port)
        {
            IP = ip;
            Port = port;
        }

        private string IP;
        private int Port;
        System.Threading.Thread sender;
        private bool issending = false;

        public void StartSending()
        {
            if (issending)
            {
                // it is already started sending. throw an exception or do something.
            }
            issending = true;
            sender = new System.Threading.Thread(SendData);
            sender.IsBackground = true;
            sender.Start();
        }

        public void StopSending()
        {
            issending = false;
            if (sender.Join(200) == false)
            {
                sender.Abort();
            }
            sender = null;
        }

        private void SendData()
        {
            System.Net.Sockets.UdpClient _sockMain = new System.Net.Sockets.UdpClient(IP, Port);
            while (issending)
            {
                // Define and assign arr_bData somewhere in class
                _sockMain.Send(arr_bData, arr_bData.Length);
            }
        }
    }
于 2012-11-08T08:14:42.827 回答
4

您可以使用 backgroundworker 线程http://www.dotnetperls.com/backgroundworker 并在 dowork() 中放置您的 while 循环。您可以使用 CancelAsync() 停止代码并设置backgroundWorker1.WorkerSupportsCancellation == true

BackgroundWorker bw = new BackgroundWorker();
          if (bw.IsBusy != true)
          {
              bw.RunWorkerAsync();

          }

          private void bw_DoWork(object sender, DoWorkEventArgs e)
          {
              // Run your while loop here and return result.
              result = // your time consuming function (while loop)
          }

          // when you click on some cancel button  
           bw.CancelAsync();
于 2012-11-08T07:52:44.183 回答
1
static bool _isSending;

static void doSend(string ip, int port)
{
    _isSending = true;

    while (_isSending)
    {
        _sockMain = new UdpClient(ip, port);
        // ...
        _sockMain.Send(arr_bData, arr_bData.Length);
    }
}

static void Stop()
{
    // set flag for exiting loop here
    _isSending = false;    
}

还要考虑在 PascalCase 中命名您的方法,即DoSend(甚至StartSending会更好)StopSending,.

于 2012-11-08T07:48:44.563 回答
0

使用BREAK语句怎么样?

于 2012-11-08T07:41:58.870 回答