Reputation: 1
I am trying to do what I think should be relatively simple, but my UI doesn't update right away.
What I need to do is when a button is clicked I need to update a label stating that a job has started, start that job, then update the label when the job is complete. However the UI always block until the job is finished so I can't do anything while I am waiting for the job to finish. Any thoughts on how to fix this?
Hey is some of my code:
protected async void TurnOff_Click(object sender, EventArgs e) {
Label1.Text = "Started";
Label1.Text = await Task.Run<string>(() => SimulateData());
}
Private string SimulateData() {
Thread.Sleep(5000); //I have tried other methods that will do work for awhile and not freeze the thread as well (neither work)
return "finished";
}
Regardless of how I run things it always seems that it will block until the job is finished then it will let me do things with the UI. I need it to automatically return as soon as the job starts then update the UI when it finishes.
Upvotes: 0
Views: 735
Reputation: 218828
This is only happening asynchronously server-side. The web server is still waiting for the response to be complete before it delivers anything to the client. Even if this did work as you expect... How would you actually expect it to work? It would deliver a response to your browser, and then what? How would it update that response that's already in your browser?
In order to conduct an asynchronous operation between the client and the server you need to use AJAX or web sockets or some asynchronous communication medium.. The way you describe the process even sounds like an ideal scenario for something like SignalR, which is a tool designed to maintain a connection between the browser and the server-side code and notify the browser of server-side messages. (Via web sockets if available, or it will transparently degrade to things like long polling where necessary.)
Upvotes: 8