一个While循环线程

时间:2012-11-08 07:39:14

标签: c# while-loop

所以我一直在尝试创建一些代码,这些代码在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);
        }
    }

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

4 个答案:

答案 0 :(得分:8)

它挂起,因为你的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);
            }
        }
    }

答案 1 :(得分: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();

答案 2 :(得分: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

答案 3 :(得分:0)

如何使用BREAK声明?