Updating my UI from a worker function

S

sklett

I have been doing research on updating the UI while doing time intensive
processing. Basically, I have a click event in my Form that will call a
member function on one of my business objects, that function that gets
called takes a long time. I read that I can't make calls to the UI from
another thread directly, so I had planned on doing the following(tell me if
this is a bad design or could be better);
1) Click event calls business object method
2) Business object starts a new thread and executes the time intensive code;
3) Business object has a reference to the UI (Form) class and uses Invoke to
call the UI's refresh function


Pseudo code
class MyForm : Form
{
BusObj busObj;

public void UpdateProgress(string str)
{
// UI STUFF
}

public void LongProcess_click(object sender, System.EventArgs e)
{
busObj.StartLongProcess();
}
}

public class BusObj
{
public void StartLongProcess( MyForm ui)
{
ui.Invoke(ui.UpdateProgress);
// do other stuff
}
}

// end fake code



Does this seem like the way that most people would do it? I'm more asking
about the general approach vs small details. For example, I just read that
I need to use a delegate with Invoke, so I couldn't call UpdateProgress
directly.

I'm just trying to nail down a solution so that I can easily launch my
various long process' and still get UI updates from them.

Thanks for reading, I hope what I want to do is clear.
-Steve
 
D

D. Yates

sklett,

Your plan will work fine and it's a matter of personal preference as to how
to implement it. If your just doing some simple work, I personally would
just spawn off a thread pool thread on a method within the form's class like
so:

using System.Threading;

// Spawn a thread to do some work
System.Threading.ThreadPool.QueueUserWorkItem(new
WaitCallback(WorkerMethod));


protected void WorkerMethod(object o)
{
// thread pool thread works its behind off.......

TS_WorkDone(true);
}


public delegate void UlSimpleBoolDelegate(bool bGoodResult);

protected void TS_WorkDone(bool bGoodResult)
{
if (this.InvokeRequired == false)
{
// Update the UI here....
}
else this.BeginInvoke(new UlSimpleBoolDelegate(TS_WorkDone), new
object[] { bGoodResult });

// Note: If you don't need to pass anything back to the UI thread, use
the MethodInvoker delegate
// since it is faster than any custom delegate that you can
create.....like so
// else this.BeginInvoke(new MethodInvoker(TS_MethodWithNoParameters),
null);
}

If its more complex, you can separate the work out into a new class and have
it spawn a thread pool thread to do the work....

It's up to you.

Dave
 

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