如何从后台工作者获取值

如何从后台工作者获取值

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

问题描述

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

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



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



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)
        {

        }

推荐答案


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


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


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

08-10 23:20