Finestra non rispondente
-
10-07-2019 - |
Domanda
Il mio codice chiama un metodo Web service che richiede alcuni minuti per eseguire l'operazione. Durante quel periodo la mia finestra non risponde e mostra uno schermo bianco completo.
Non voglio il metodo call da un thread diverso.
È il modo migliore per gestirlo?
Ambiente: C #, servizio web
Soluzione
È possibile effettuare la richiesta su un thread separato, che lascerà il thread dell'interfaccia utente reattivo. Al termine dovrai sincronizzare la risposta con il thread dell'interfaccia utente.
Altri suggerimenti
BackgroundWorker è tuo amico.
Ecco un esempio di come uso un BackgroundWorker con un servizio Web. Fondamentalmente, non è possibile eseguire operazioni intensive sul lato dell'interfaccia utente senza utilizzare un thread separato. BackgroundWorker è il modo migliore per eseguire su un thread separato.
Per avere un'interfaccia utente reattiva, è necessario utilizzare un altro thread.
Ma se usi Visual Studio, la classe client generata ha firme di metodo asincrone che lo farebbero per te. Se il tuo metodo è " GetData " ;, quindi dovresti avere un metodo chiamato " GetDataAsync " che non congelerebbe la tua finestra.
Ecco un esempio:
WsClient client;
protected override void Load() {
base.Onload();
client = new WsClient();
client.GetDataCompleted += new GetDataCompletedEventHandler(client_GetDataCompleted);
}
//here is the call
protected void Invoke()
{
client.GetDataAsync(txtSearch.Text);
}
//here is the result
void client_GetDataCompleted(object sender, GetDataCompletedEventArgs e)
{
//display the result
txtResult.Text = e.Result;
}