2012-03-21 84 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