मैं BackgroundWorker
साथ धागा बनाते हैं, और पाश में मैं हर बार की जाँच करता है, तो CancellationPending
सच है या नहीं, इस तरह:एप्लिकेशन निष्क्रिय होने पर पृष्ठभूमिवर्कर थ्रेड कितना करीब है?
public MainPage()
{
InitializeComponent();
bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
private void ButtonStart_Click(object sender, RoutedEventArgs e)
{
if (bw.IsBusy != true)
{
bw.RunWorkerAsync();
}
}
private void ButtonCancel_Click(object sender, RoutedEventArgs e)
{
if (bw.WorkerSupportsCancellation)
{
bw.CancelAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 100; i++)
{
Debug.WriteLine("The tread is working");
if (worker.CancellationPending)
{
e.Cancel = true;
bw.CancelAsync();
break;
}
else
{
System.Threading.Thread.Sleep(500);
worker.ReportProgress(i);
}
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
tbProgress.Text = "Canceled";
}
else if (e.Error != null)
{
tbProgress.Text = "Error: " + e.Error.Message;
}
else
{
tbProgress.Text = "Done";
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
tbProgress.Text = e.ProgressPercentage.ToString() + "%";
}
जब आवेदन कर दिया गया है, धागा, बंद नहीं किया गया था यह निरस्त किया जाता है और अपवाद होता है। आवेदन निष्क्रिय होने पर BackgroundWorker
के साथ कितने करीब धागे?
क्या आपने इसे आजमाया है? क्या आपको वह चाहिए जो आपको चाहिए? –
@ liho1ey हां, मैंने कोशिश की और whet अनुप्रयोग निष्क्रिय मैं अपवाद प्राप्त किया। मैं इन कोड को पृष्ठ xaml.cs में आवेदन स्तर पर नहीं लिखता हूं। –
ठीक है, लेकिन क्या आप 'CancelAsync() 'को कॉल कर रहे हैं? –