A While Loop Thread

19,954

Solution 1

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);
            }
        }
    }

Solution 2

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();

Solution 3

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;    
}

Also consider to name your methods in PascalCase, i.e. DoSend (even StartSending will be better), StopSending.

Share:
19,954

Related videos on Youtube

Daaksin
Author by

Daaksin

Hey, I'm Daaksin. Programming is the best way to both relax and spin your head in circles for hours on end. Progamming sometimes causes lack of sleep due to frustration over bugs and such, but its well worth it. Here are the languages I do: C# .NET (Usually 2.0) C++ (I lose the most sleep over this one) Python Java I favour writing network applications, advanced chat programs, basic 2D topdown LAN games etc. Oh yeah, and I'm Australian. Chuck anotha shrimp on tha barbie, ay! No I don't ride Kangaroos to work, but that'd be awesome!

Updated on September 16, 2022

Comments

  • Daaksin
    Daaksin over 1 year

    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?

    • Gianni B.
      Gianni B. over 11 years
      If you never change the variable isSending, you will never go out from you loop
  • TechDo
    TechDo over 11 years
    Please check the links msdn.microsoft.com/en-us/library/2aeyhxcd(v=vs.71).aspx, dotnetperls.com/while. Break statement can be used to terminate while loop.
  • Daaksin
    Daaksin over 11 years
    I only want to exit it when a button is clicked, otherwise it must keep going?
  • Daaksin
    Daaksin over 11 years
    Thank you for this, but it hangs? The program receiving still get's data.
  • AmazingDreams
    AmazingDreams over 11 years
    Then define a button click event which changes a boolean variable; isSending.
  • Sergey Berezovskiy
    Sergey Berezovskiy over 11 years
    Because you do sending in a loop. After current sending completes, next one will not occur.
  • Oliver
    Oliver over 11 years
    This won't work in this way. You need to set the WorkerSupportsCancellation and you have to check the CancellationPending within your loop. A complete example can be found at MSDN.
  • Daaksin
    Daaksin over 11 years
    I like this! Thank you Taner!
  • Alexander Petrov
    Alexander Petrov almost 6 years
    It's awful! volatile is not mentioned in any answer.
  • Laurent
    Laurent almost 3 years
    @AlexanderPetrov that might be because the volatile keyword was added years later !