2009-08-17 22 views
9

Come posso segnalare una stringa (come "ora ricerca file ...", "selezione selezionata ...") torna al mio windows.form da un backgroundWorker così come una percentuale. Inoltre, ho una grande classe che contiene il metodo che voglio eseguire in backgroundWorker_Work. Posso chiamarlo per Class_method(); ma non sono quindi in grado di riportare la mia percentuale eseguita o qualcosa della classe chiamata, solo dal metodo backgroundWorker_Work.C# backgroundWorker segnala una stringa?

Grazie!

risposta

22

Sto assumendo WCF hanno anche il metodo

public void ReportProgress(int percentProgress, Object userState); 

Quindi basta usare l'UserState per segnalare la stringa.

private void worker_DoWork(object sender, DoWorkEventArgs e) 
{ 
//report some progress 
e.ReportProgress(0,"Initiating countdown"); 

// initate the countdown. 
} 

E si otterrà che "Avvio del conto alla rovescia" stringa indietro nel caso in ProgressChanged

private void worker_ProgressChanged(object sender,ProgressChangedEventArgs e) 
{ 
    statusLabel.Text = e.UserState as String; 
} 
0

utilizzare un delegato.

9

È possibile utilizzare il parametro userState del metodo ReportProgress per segnalare le stringhe.

Ecco un esempio da MSDN:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
{ 
    // This method will run on a thread other than the UI thread. 
    // Be sure not to manipulate any Windows Forms controls created 
    // on the UI thread from this method. 
    backgroundWorker.ReportProgress(0, "Working..."); 
    Decimal lastlast = 0; 
    Decimal last = 1; 
    Decimal current; 
    if (requestedCount >= 1) 
    { AppendNumber(0); } 
    if (requestedCount >= 2) 
    { AppendNumber(1); } 
    for (int i = 2; i < requestedCount; ++i) 
    { 
     // Calculate the number. 
     checked { current = lastlast + last; } 
     // Introduce some delay to simulate a more complicated calculation. 
     System.Threading.Thread.Sleep(100); 
     AppendNumber(current); 
     backgroundWorker.ReportProgress((100 * i)/requestedCount, "Working..."); 
     // Get ready for the next iteration. 
     lastlast = last; 
     last = current; 
    } 

    backgroundWorker.ReportProgress(100, "Complete!"); 
}