keeping UI responsive

B

blueturtle

Hi,

I'm newbie to C#, and I would like to know what is the common solution
to a problem that I encounter.

The scenario:
Performing a long task, without blocking the UI thread, so it will stay
responsive.
The long task is done in a different thread.

According to want I've read, in C# it is performed using IAsyncResult
and BeginInvoke.
This solves the issue of blocking, however it requires me to use
delegates to receive the result of the task,
so the code becomes "event driven".

I'm looking for something else: do the task in different thread, wait
for event and keep UI responsive, all in one time.
So the code of UI will treat the method calls, as if they are
synchronous.

This can be achieved in C++ by "Wait and keep pumping messages":

pseudo:
while (true)
{
while (PeekMessage(...)
DispatchMessage(...);
MsgWaitForMultipleObjects(...);
}

I've read somewhere the WaitOne() is implemented using
MsgWaitForMultipleObjects, so I've tried:

ar = d.BeginInvoke(params, new AsyncCallback(MyCallback) ,null);
ar.AsyncWaitHandle.WaitOne();

but it makes the UI very unresponsive (painting and mouse),
I guess that's because I cannot control the filter of the messages.

How can it be done in C# ?
Am I doing something wrong ?

Thanks for any help,
Si.
 
J

Jon Skeet [C# MVP]

I'm newbie to C#, and I would like to know what is the common solution
to a problem that I encounter.

The scenario:
Performing a long task, without blocking the UI thread, so it will stay
responsive.
The long task is done in a different thread.

According to want I've read, in C# it is performed using IAsyncResult
and BeginInvoke.

Well, updating the UI is usually done using Control.Invoke or
Control.BeginInvoke, but starting the long-running thread can be done
in any number of ways.
This solves the issue of blocking, however it requires me to use
delegates to receive the result of the task,
so the code becomes "event driven".

I'm looking for something else: do the task in different thread, wait
for event and keep UI responsive, all in one time.

<snip>

I dare say there are ways of doing it, but it goes against the way that
Windows Forms (and Windows in general) was designed to work.

Could you explain why you don't want to just use a call-back, so that
when the long-running thread has finished doing something, a call is
made in the UI thread? What's the advantage of a separate, complicated
way of doing things?

See http://www.pobox.com/~skeet/csharp/threads/winforms.shtml for more
information about threading in Windows Forms.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top