c# - Thread Blocking the UI -
i following example c# in nutshell. according text following code supposed non blocking, find form not display until 5 seconds have passed.
private void form1_load(object sender, eventargs e) { var tcs = new taskcompletionsource<int>(); new thread(() => {thread.sleep(5000); tcs.setresult(42); }).start(); task<int> task = tcs.task; messagebox.show(task.result.tostring()); }
i have feeling it's thread.sleep() , instead of putting new thread sleep, it's putting main thread sleep.
why blocking ui thread?
when call task.result.tostring()
(in messagebox.show
) task
class has mechanism waits task finished before giving result (as doesn't have until task
finishes. here's proof:
private void form1_load(object sender, eventargs e) { var tcs = new taskcompletionsource<int>(); new thread(() => {thread.sleep(5000); tcs.setresult(42); }).start(); task<int> task = tcs.task; thread.sleep(2500); messagebox.show("waited 2.5secs on ui thread."); messagebox.show(task.result.tostring()); }
you see shows 2.5sec message box before messagebox 42. (in fact, 2.5 seconds before that).
what looking this:
private void form1_load(object sender, eventargs e) { var tcs = new taskcompletionsource<int>(); new thread(() => {thread.sleep(5000); tcs.setresult(42); }).start(); task<int> task = tcs.task; task.continuewith(t => messagebox.show(t.result.tostring())); }
this not freeze ui thread.
Comments
Post a Comment