HttpPost上的计时器奇怪的行为

时间:2017-07-16 07:49:23

标签: c# timer httprequest

我已经编写了以下代码来在网站上发布一些文章:

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

本守则昨天正在运作,但今天当我发表一些新文章(5篇文章)时,我注意到第一篇和第二篇文章已经发表但第三篇文章发表了10多次,然后我停止了该程序看看有什么问题。 为了排除故障,我在以下行中创建了一个分隔线:

if (counter >= postList.Count)

并且意识到第三个tick永远不会结束,并且在第二次按下它后,Visual Studio debug->继续按钮被禁用,并且在断点线中,visual studio告诉我frmMain.tick正在进行中。 我发现第三篇文章的唯一区别是字符串长度更多。 但是,我仍然没有得到问题,没有错误,没有例外。

*******编辑*******

我添加了类似于opewix的try catch块,但仍然没有例外,并且发布第三篇文章一直持续到我停止调试..

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

        }

有关更多信息,这是我正在使用的PHP代码:

<?php
/****************       INCLUDES     ******************/
require_once "../code/functions.php";
require_once "../code/entities.php";
require_once "../code/DAL.php";

/*****************************       CHECKING PARAMS     *******************************/

//if(!isset($_POST["uw"]) || sha1($_POST["uw"])!="a4cc225e13f9ea1c02091e3471a963975fdf4e13")
//{
//  exit("HTTP 404");
//}

if(isPostBack() && isset($_GET["action"]) && $_GET["action"]=="insert"
 && isset($_POST["content"]) && $_POST["content"]!=""
 && isset($_POST["title"]) && $_POST["title"]!="")
Http_Post_Insert($_POST["title"],$_POST["content"]);
else
    print_r($_POST);

if(isPostBack() && isset($_GET["action"]) && $_GET["action"]=="delete"  && isset($_GET["pid"]) && is_numeric($_GET["pid"]))
Http_Get_Delete($_GET["pid"]);

/*****************       ACTIONS      ******************/

function Http_Get_Delete($pid){}


function Http_Post_Insert($title,$content)
{


$preview=isset($_POST['preview'])?$_POST['preview']:"http://";
$CatID=isset($_POST["cid"])?$_POST["cid"]:"-1";
$date_time=isset($_POST["date_time"])?$_POST["date_time"]:date('Y-m-d H:i:s');

$private=0;
$PT=$title;
$PC=$content;
$PC2=$content;



$d=getdate();
$pJdate=gregorian_to_jalali($d['year'],$d['mon'],$d['mday']);
$pDate=(int)("$pJdate[0]"."$pJdate[1]"."$pJdate[2]");
$pTime=$d['seconds']." : ".$d['minutes']." : ".$d['hours'];

try
{
$p=new Post();
$res=$p->add($PT,$preview,$PC,$PC2,$pDate,$pTime,$date_time,$CatID,$private=false);
echo $res;
}
catch(Exception $ex)
{
    echo $ex->getMessage();
}
}

?>

2 个答案:

答案 0 :(得分:1)

您必须将Tick处理程序包装到try-catch块中,然后设置断点以捕获块,然后您将看到异常。在提交请求后,您似乎没有获得异常,而且计数器也没有增加。

答案 1 :(得分:0)

Like Enigmativity表示,Application.DoEvents();是问题!!! 我仍然不相信我的程序正在运行,但这是真的,每当我评论代码时,他说我得到了消息&#34; Done&#34;每次我取消注释该代码时,刻度永远不会结束,并且发布第三篇文章继续... 我使用该代码的原因是为了更新lbl_status文本,因为在某些其他程序的某些情况下,我看到Windows控件在我使用Application.DoEvents()之前不会更新。看来我好像应该更多地研究这种方法。谢谢EveryOne,