如何从后台工作者获取值 [英] How to get the value from a background worker

查看:78
本文介绍了如何从后台工作者获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个后台工作程序,它在表单加载时运行无限循环。

我需要帮助来获取循环的索引并在用户单击按钮时显示标签。



这是我的后台工作人员,从表格加载开始。



I have a background worker which runs an infinite loop starting on form load.
I need help to get the index of the loop and show in a lable when the user clicks on a button.

here is my background worker which starts on form load.

public Form1()
        {
            InitializeComponent();
           backgroundWorker1.RunWorkerAsync();

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

            int i = 0;
            DateTime a;
          while ( i <= 1000)
            {
                a = DateTime.Now;
                if (i == 999)
                {
                    i = 0;

                }
                e.Result = a;

          }

        }
       private void btnShowIndex_Click(object sender, EventArgs e)
        {
           
        }

推荐答案

我强烈建议你阅读这篇 MSDN 页面:如何:对Windows窗体控件进行线程安全调用 [ ^ ]。
I strongly suggest you reading this MSDN page: "How to: Make Thread-Safe Calls to Windows Forms Controls"[^].


while (i <= 1000) {
   // ...
   e.Result = a;
   backgroundWorker1.ReportProgress(i);
}



将允许您将while循环中的当前索引传递给适当的事件处理程序。



您必须为要捕获的ProgressChanged事件创建一个处理程序:


will allow you to pass the current index in your while loop to an appropriate event handler.

You have to create an handler for the ProgressChanged event to be catched:

// During initialization:
backgroundWorker1.ReportProgress += backgroundWorker1_ProgressChanged;

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
   // You will get the current index with
   int index = e.ProgressPercentage;
}


您必须在课程级别对您的计数器进行十分转换。

You have to decalre your counter in class level.
public class Form1
{
int i =0;
public Form1()
        {
            InitializeComponent();
           backgroundWorker1.RunWorkerAsync();
 
        }
 
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
 
            
            DateTime a;
            while ( i <= 1000)
            {
                a = DateTime.Now;
                if (i == 999)
                {
                    i = 0;
 
                }
                e.Result = a;
 
          }
 
        }
       private void btnShowIndex_Click(object sender, EventArgs e)
        {
           label.Text = i.ToString();
        }
}


这篇关于如何从后台工作者获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆