Sto cercando di capire come aggiornare un'interfaccia utente da un evento mentre si utilizza il modello async/await. Di seguito è riportato il codice di prova che sto utilizzando su un'app WinForm. Non sono nemmeno sicuro che questo sia il modo giusto per farlo. Cosa è necessario per consentire al metodo pwe_StatusUpdate di aggiornare l'IU? L'errore dell'operazione incrociata viene generato lì.Aggiornamento dell'interfaccia utente dagli eventi che utilizzano asyc attendere
Grazie per la lettura.
// calling code
ProcessWithEvents pwe = new ProcessWithEvents();
pwe.StatusUpdate += pwe_StatusUpdate;
await pwe.Run();
void pwe_StatusUpdate(string updateMsg)
{
// Error Here: Cross-thread operation not valid: Control '_listBox_Output' accessed from a thread other than the thread it was created on.
_listBox_Output.Items.Add(updateMsg);
}
-
// Class with long running process and event
public delegate void StatusUpdateHandler(string updateMsg);
public class ProcessWithEvents
{
public event StatusUpdateHandler StatusUpdate;
public async Task Run()
{
await Task.Run(() =>
{
for (int i = 0; i < 10; i++)
{
RaiseUpdateEvent(String.Format("Update {0}", i));
Thread.Sleep(500);
}
});
}
private void RaiseUpdateEvent(string msg)
{
if (StatusUpdate != null)
StatusUpdate(msg);
}
}
-
È 'ProcessWithProgress' nella sezione' // codice chiamante' che dovrebbe essere 'ProcessWithUpdates', invece? –
@Brock: Yup. Modificato. –