Search code examples
c#timerhttprequest

Timer strange behavior on HttpPost


I have written the following code to publish some articles on the Website:

private void btnTransfer_Click(object sender, EventArgs e)
{
    //some codes here
    counter = 0;
    t = new System.Windows.Forms.Timer();
    t.Interval = 2000;
    t.Tick += t_Tick;
    t.Start();
}

int counter;

void t_Tick(object sender, EventArgs e)
{
    string cid = cb_destinationSubject.Items[cb_destinationSubject.SelectedIndex].ToString().Split('|')[0];

    var wb = new WebClient();
    var data = new NameValueCollection();

    data["cid"] = cid;
    data["title"] =tb_titlePrefix.Text+ postList.ElementAt(counter)[0]+tb_titleSuffix.Text;
    data["content"] =tb_textPrefix.Text+ postList.ElementAt(counter)[1]+tb_textSuffix.Text;
    if (listBox_images.Items.Count>0)
    data["preview"] = listBox_images.Items[new Random().Next(listBox_images.Items.Count)].ToString();

    DateTime dt = selector_first_publish.Value.Value;
    dt += TimeSpan.FromMinutes((double)(counter * nud_delay.Value));

    data["date_time"] = dt.ToString("yyyy-MM-dd HH:mm:ss");

    var response = wb.UploadValues(Settings.ApiUrl+"/api/post.php?action=insert","post", data);
    var responseString = Encoding.UTF8.GetString(response);

    tb_debug.Text += responseString + "\r\n";

    if(responseString.Length>5)
    lbl_status.Text = responseString;
    else
        lbl_status.Text =counter.ToString()+" articles has been saved successfully !";

    counter++;
    if (counter >= postList.Count)
    {
        counter = 0;
        t.Stop();
        MessageBox.Show("Done!");
        System.Diagnostics.Process.Start(Settings.ApiUrl);
    }       
}

This Code was working yesterday, but today when I was publishing some new articles (5 articles) I noticed that the first and second article has been published but the third one has been published more than 10 times, then I stopped the program to see what's the problem. For troubleshooting I created a break line in the following line:

if (counter >= postList.Count)

And realized the third tick never ends, and Visual Studio debug->continue button gets disabled after the pressing it for the second time, and in the break point line visual studio tells me that frmMain.tick is in process. I figured out that the only difference of the third article is that the string length of that is much more. But still, I don't get what the problem is, no errors, no exceptions.

******* EDIT *******

I added try catch block like opewix said, but still there is no exceptions,and publishing the third articles goes on until I stop debuging..

 void t_Tick(object sender, EventArgs e)
        {
            try
            { 
            string cid = cb_destinationSubject.Items[cb_destinationSubject.SelectedIndex].ToString().Split('|')[0];

            var wb = new WebClient();
            var data = new NameValueCollection();

            data["cid"] = cid;
            data["title"] =tb_titlePrefix.Text+ postList.ElementAt(counter)[0]+tb_titleSuffix.Text;
            data["content"] =tb_textPrefix.Text+ postList.ElementAt(counter)[1]+tb_textSuffix.Text;
            if (listBox_images.Items.Count>0)
            data["preview"] = listBox_images.Items[new Random().Next(listBox_images.Items.Count)].ToString();

            DateTime dt = selector_first_publish.Value.Value;
            dt += TimeSpan.FromMinutes((double)(counter * nud_delay.Value));

            data["date_time"] = dt.ToString("yyyy-MM-dd HH:mm:ss");

            //wb.UseDefaultCredentials = true;
            //System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
            var response = wb.UploadValues(Settings.ApiUrl+"/api/post.php?action=insert","post", data);
            var responseString = Encoding.UTF8.GetString(response);



            tb_debug.Text += responseString + "\r\n";

            if(responseString.Length>5)
            lbl_status.Text = responseString;
            else
                lbl_status.Text =counter.ToString()+" articles has been saved successfully !";

            Application.DoEvents();

            counter++;
            if (counter >= postList.Count)
            {
                counter = 0;
                t.Stop();
                MessageBox.Show("انتقال انجام شد");
                System.Diagnostics.Process.Start(Settings.ApiUrl);
            }
                }
            catch(Exception ex)
            {
                throw ex;
            }

        }

For more information this is the php code I'm using:

 /*.. PHP code was unnecessary so is removed ..*/

Solution

  • Like Enigmativity said, Application.DoEvents(); was the problem !!! I still don't believe that my program is working, But that's true , Every time I comment the code he said I get the message "Done" and every time I uncomment that code the tick never ends and publishing the third articles goes on... The reason I used that code was to update the lbl_status Text,Because In some cases in some other programs I've seen Windows Controls doesn't get updated until I use that Application.DoEvents() ..It seems I should study more about this method..Thanks EveryOne,