Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A While Loop Thread

Tags:

c#

while-loop

So I've been trying to create a bit of code that sends data on a while loop, specifically an alive packet to a server through a 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);
        }
    }

But when I call the "Stop" method, it gets stuck in a constant loop and doesn't come out. How can I put the while loop into a Thread? So I can abort the thread on stop, cancelling the loop?

like image 591
Daaksin Avatar asked Dec 08 '22 19:12

Daaksin


2 Answers

It hangs because your doSend method works on UI thread. You can use something like the below class to make it run on a seperate thread or you can use 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);
            }
        }
    }
like image 118
fofik Avatar answered Dec 31 '22 14:12

fofik


You can use the backgroundworker thread http://www.dotnetperls.com/backgroundworker and inside dowork() put your while loop. You can stop the code by using CancelAsync() and set 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();
like image 37
varun257 Avatar answered Dec 31 '22 16:12

varun257