आप इस तरह की आवश्यकताओं के लिए BackgroundWorker का उपयोग कर सकते हैं। नीचे एक नमूना है जो updates a label status based on percentage task [long running] completion
है। साथ ही, एक नमूना व्यवसाय वर्ग है जो कुछ मान निर्धारित करता है और मान ProgressChanged
हैंडलर के माध्यम से यूआई पर वापस सेट किया जाता है। DoWork
वह जगह है जहां आप अपना लंबा चलने वाला कार्य तर्क लिखते हैं। एक Winforms ऐप & पर एक लेबल और पृष्ठभूमि कार्यकर्ता घटक जोड़ने के बाद नीचे दिए गए कोड को कॉपी-पेस्ट करें, इसे एक शॉट दें। आप विभिन्न हैंडलर [RunWorkerCompleted, ProgressChanged, DoWork]
पर डीबग कर सकते हैं और InitWorker
विधि पर एक नज़र डालें। cancellation feature
पर भी ध्यान दें।
using System.ComponentModel;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form3 : Form
{
private BackgroundWorker _worker;
BusinessClass _biz = new BusinessClass();
public Form3()
{
InitializeComponent();
InitWorker();
}
private void InitWorker()
{
if (_worker != null)
{
_worker.Dispose();
}
_worker = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
_worker.DoWork += DoWork;
_worker.RunWorkerCompleted += RunWorkerCompleted;
_worker.ProgressChanged += ProgressChanged;
_worker.RunWorkerAsync();
}
void DoWork(object sender, DoWorkEventArgs e)
{
int highestPercentageReached = 0;
if (_worker.CancellationPending)
{
e.Cancel = true;
}
else
{
double i = 0.0d;
int junk = 0;
for (i = 0; i <= 199990000; i++)
{
int result = _biz.MyFunction(junk);
junk++;
// Report progress as a percentage of the total task.
var percentComplete = (int)(i/199990000 * 100);
if (percentComplete > highestPercentageReached)
{
highestPercentageReached = percentComplete;
// note I can pass the business class result also and display the same in the LABEL
_worker.ReportProgress(percentComplete, result);
_worker.CancelAsync();
}
}
}
}
void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
// Display some message to the user that task has been
// cancelled
}
else if (e.Error != null)
{
// Do something with the error
}
}
void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Text = string.Format("Result {0}: Percent {1}",e.UserState, e.ProgressPercentage);
}
}
public class BusinessClass
{
public int MyFunction(int input)
{
return input+10;
}
}
}
स्रोत
2012-07-16 09:03:21
मैं BackgroundWorker का प्रयोग करेंगे। – Tomtom
यदि आपको केवल एक अन्य धागे की आवश्यकता है तो मैं पृष्ठभूमि कार्यकर्ता का उपयोग करूंगा, वे उपयोग करने में बहुत आसान हैं और अधिकांश कड़ी मेहनत की गई है, जो आपको कार्य पूरा करने के विभिन्न चरणों के लिए सीधे आगे की घटनाओं के साथ प्रदान करती है। – ThePower
पुन: उपयोग करके आपका क्या मतलब है? –