2012-03-21 82 views
0

Delay.cs螺紋方法與返回值在C#

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading; 

namespace LearnThread 
{ 
    class Delay 
    { 
     public int Convert() 
     { 
      int ErrorCode = 1; 
      //something 
      //takes long time. about 9 hours. 
      return ErrorCode; 
     } 
    } 
} 

Form1.cs的

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Threading; 

namespace LearnThread 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void btnStart_Click(object sender, EventArgs e) 
     { 
      Delay delay = new Delay(); 
      Thread t = new Thread(delay.Convert); 
      //something 
      MessageBox.Show("Success"); 
     } 
    } 
} 

時滯延遲=新的延遲();在這裏是錯誤的,因爲它期望返回值。因爲它包含errorcode,所以我需要返回值。我怎樣才能做到這一點?後臺工作者比Thread更好?請幫忙。 (當delay.Convert()正在運行時,我不應該失去對窗體的控制。)

回答

2

使ErrorCode成爲類成員。這樣你可以在之後得到它。

class Delay 
{ 
    public int ErrorCode { get; private set; } 
    public void Convert() 
    { 
     ErrorCode = 1; 
     ... 
    } 
} 


private void btnStart_Click(object sender, EventArgs e) 
{ 
    Delay delay = new Delay(); 
    Thread t = new Thread(delay.Convert); 
    //something 
    int error = delay.ErrorCode; 
    MessageBox.Show("Success"); 
} 
+1

只是一個警告。這些代碼片段完成這項工作。因爲在C#中設置ErrorCode爲1是非常容易的任務。但是,如果您在「Convert()」方法中花費太多時間(假設中端PC需要5秒),您會在btnStart_Click()中得到ErrorCode錯誤。因爲你沒有調用線程連接,所以它遠離主線程,並且你沒有等待線程完成某些操作......所以,在「// something」的行中,你應該爲此做點什麼:) – 2012-07-08 02:43:03

4

正如Juergen所述,您可以使ErrorCode成爲類成員,然後在線程完成執行後訪問它。如果您試圖並行運行多個Convert,這將需要您創建Delay類的新實例。

您也可以使用委託的返回值獲得在btnStart_Click功能的變量,如下所示:

private void button1_Click(object sender, EventArgs e) 
     { 
      Delay delay = new Delay(); 
      int delayResult = 0; 
      Thread t = new Thread(delegate() { delayResult = delay.Convert(); }); 
      t.Start(); 
      while (t.IsAlive) 
      { 
       System.Threading.Thread.Sleep(500); 
      } 
      MessageBox.Show(delayResult.ToString()); 
     } 

如果計劃運行並行轉換在這裏,你將不得不創造儘可能多的地方根據需要變量或以其他方式處理它。

+0

我認爲這是更好的答案,我解釋了爲什麼在「juergen d」的答案。並感謝那個被切斷的Manoj。 – 2012-07-08 02:45:21