1

I am using a background for my sms application.

I have created an application which needs to send messages continously.

When i use background.My application gets hanged i dont know why it is,

my code is

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
   //mycode
}

private void backgroundWorker1_RunWorkerCompleted(
    object sender, RunWorkerCompletedEventArgs e)
{
    backgroundWorker1.CancelAsync();
    backgroundWorker1.RunworkAsync();
}

later i have tried this

public void Thread()
{
    Thread D = new Thread(BackgroundCode);
    D.Start();
}

public void BackgroundCode()
{
    for (int i5 = 1; i5 > 0; i5 += 1)
    {
       //mycode
    }

}

this two works fine for 2 or 3 min but after that it gets hang.

Please can anyone please help me.

Thanks In Advance.

Arshiya
  • 45
  • 8

2 Answers2

1

try this

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
   while(true)
   {
       //your sms code
       //call CancelAsync() here if you want to get out!!!!
   }
}

private void backgroundWorker1_RunWorkerCompleted(
    object sender, RunWorkerCompletedEventArgs e)
{
   //donot include RunWorkerAsync() and CancelAsync() in this method!
}
Anirudha
  • 32,393
  • 7
  • 68
  • 89
0

This is a bit of a long post, but it seems to fit your problem quite well.

Basically, it shows how you can do this with a BackgroundWorker or the Task Parallel Library (TPL would be my suggestion)

For the TPL you create a ProgressReporter class that will be used in the class to pass messages back to the main thread, while continuing to run the task.

Also, your for loop will never end because it is saying to run while i5 is greater than 0. And, it starts at 1 and counts up, so it will never be less than or equal to zero. That will fix your hanging, but once you fix that, the progress reporter from the blog class should help with the rest.

Justin Pihony
  • 66,056
  • 18
  • 147
  • 180