2017-07-16 62 views
0

我寫了下面的代碼發佈在網站上的一些文章:定時器奇怪的行爲

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) 

,實現了兩個刻度永遠不會結束,和Visual Studio調試 - >繼續按鈕,按下它後第二次被禁用,並在斷點線視覺工作室告訴我,​​正在處理中。 我發現第三篇文章的唯一區別是字符串的長度要多得多。 但是,我仍然沒有得到什麼問題,沒有錯誤,沒有例外。

*******編輯*******

我說喜歡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(); 
} 
} 

?> 
+1

你需要什麼定時器? – dnickless

+0

我需要它多次調用相同的方法:) – Vahid2017

+1

如果你想要相同的代碼並行運行,比定時器有更好的選擇,例如, ThreadPool。我懷疑你的邏輯有一個基本缺陷,因爲你使用計數器變量。您在任何點擊後將其重置爲零,然後在您的定時器方法中測試它看起來很奇怪。 – dnickless

回答

0

Like Enigmativity說,Application.DoEvents();是問題! 我仍然不相信我的程序正在工作,但的確如此,每次我評論他所說的代碼時,我都會收到消息「完成」,並且每次我取消註釋該代碼時,tick都不會結束,並且發佈第三篇文章... 我使用該代碼的原因是更新lbl_status文本,因爲在某些其他程序中,我看到Windows控件不會更新,直到我使用該Application.DoEvents()..它似乎我應該學習更多關於這種方法..謝謝EveryOne,

1

你要包裝你的節拍處理成try-catch塊,然後設置一個斷點catch塊,那麼你會選擇e例外。在提交請求和計數器不增加後,您似乎收到異常。

+0

謝謝,但是如果我收到異常,爲什麼VS不通知我?爲什麼程序繼續發佈第三篇文章? – Vahid2017

+1

Timer組件捕獲並抑制事件處理程序爲Elapsed事件拋出的所有異常。這個異常中斷執行,你的計數器永遠不會增加,計時器永遠不會停止 – opewix

+0

謝謝Opewix,我添加了try catch塊但沒有得到任何異常,它只是連續發佈第三篇文章... – Vahid2017