9

Comment puis-je signaler une chaîne (comme "now search file. ...", "Found selection ....") À mon windows.form à partir d'un backgroundWorker ainsi que d'un pourcentage. De plus, j'ai une grande classe qui contient la méthode que je veux exécuter dans backgroundWorker_Work. Je peux l'appeler par Class_method(); mais je suis alors incapable de signaler mon pourcentage fait ou quelque chose de la classe appelée, seulement de la méthode backgroundWorker_Work.C# backgroundWorker signale une chaîne?

Merci!

Répondre

22

Je suppose WCF ont également la méthode

public void ReportProgress(int percentProgress, Object userState); 

Donc il suffit d'utiliser le userState pour signaler la chaîne.

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

// initate the countdown. 
} 

Et vous obtiendrez cette chaîne "Initier à rebours" retour dans l'événement ProgressChanged

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

utilisez un délégué.

9

Vous pouvez utiliser le paramètre userState de la méthode ReportProgress pour signaler ces chaînes.

Voici un exemple de 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!"); 
} 
Questions connexes