473,323 Members | 1,551 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,323 software developers and data experts.

Update UI from Background thread

RSH
Hi,

I have an Asynchronus process that is reporting back to the UI at regular
intervals. I read several posts on how to use delegates to make this
happen. But for some reason my application just hangs, nothing being
written it just hangs. when I comment out the "Invoke(new
UpdateTextCallback(UpdateText));" it works fine.

What am I missing?

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

EventMonitor.ProcessMonitor += new ProcessMonitorHandler(DisplayEvents);

Party m_Party = new Party();

}

private void DisplayEvents(object sender, ProcessEventArgs e)

{

if (InvokeRequired)

{

System.Diagnostics.Debug.WriteLine("HIT!");

Invoke(new UpdateTextCallback(UpdateText));

}

else

{

richTextBox1.Text += e.EventArg + "\r\n";

}

Application.DoEvents();

}

private void UpdateText(object sender, ProcessEventArgs e)

{

System.Diagnostics.Debug.WriteLine("HIT!");

richTextBox1.Text += e.EventArg + "\r\n";

}

public delegate void UpdateTextCallback(object sender, ProcessEventArgs e);

public delegate void ProcessMonitorHandler(object sender, ProcessEventArgs
e);

}



public static class EventMonitor

{

public static event ProcessMonitorHandler ProcessMonitor;

public static void BroadcastEvent(string Event)

{

OnEvent(Event);

}

static void OnEvent(string Event)

{

if (ProcessMonitor != null)

{

ProcessEventArgs e = new ProcessEventArgs();

e.EventArg = Event;

ProcessMonitor(null, e);

}

}

}
Dec 14 '07 #1
4 2357
On Fri, 14 Dec 2007 12:12:17 -0800, RSH <wa*************@yahoo.comwrote:
I have an Asynchronus process that is reporting back to the UI at regular
intervals. I read several posts on how to use delegates to make this
happen. But for some reason my application just hangs, nothing being
written it just hangs. when I comment out the "Invoke(new
UpdateTextCallback(UpdateText));" it works fine.
Well, you didn't post a complete code sample. So no one can say for sure
what's going on.

But my suspicion is that even though you're using (you say) a separate
thread for the async processing, your Click event handler doesn't return
right away but instead waits for the processing to complete. With the
main GUI thread blocked, there's no way for the call to Invoke() to
complete, and thus you get a deadlock.

If you want a better answer, you need to post a concise-but-complete
sample of code that reliably demonstrates the problem.

Pete
Dec 14 '07 #2
RSH
Okay sorry...

Form Code:
namespace TestObjectInteraction

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

EventMonitor.ProcessMonitor += new ProcessMonitorHandler(DisplayEvents);

Party m_Party = new Party();

}

private void DisplayEvents(object sender, ProcessEventArgs e)

{

System.Diagnostics.Debug.WriteLine(e.EventArg);

if (this.richTextBox1.InvokeRequired)

{

this.richTextBox1.Invoke(new ProcessMonitorHandler(DisplayEvents), sender,
e);

}

else

{

richTextBox1.Text += e.EventArg + "\r\n";

}

Application.DoEvents();

}

}

}

//Event Monitor Class

public static class EventMonitor

{

public static event ProcessMonitorHandler ProcessMonitor;

public static void BroadcastEvent(string Event)

{

OnEvent(Event);

}

static void OnEvent(string Event)

{

if (ProcessMonitor != null)

{

ProcessEventArgs e = new ProcessEventArgs();

e.EventArg = Event;

ProcessMonitor(null, e);

}

}

}

// Baker Class

public class Baker

{

private CookBook m_CookBook = new CookBook();

private Oven m_Oven = new Oven();

private Recipe m_Recipe;

private MixingBowl m_MixingBowl = new MixingBowl();

private IBakingPlatform m_BakingPlatform;

private BakedGoods m_BakedGoods;

private bool bDoneMixing;

private bool bOvenPreheated;

public event BakedGoodServingHandler Served;

public void BakeCookies()

{

EventMonitor.BroadcastEvent("Baker is looking up recipe...");

m_Oven.DoneCooking += new FinishedCookingHandler(OnDoneCooking);

m_Oven.TempChange += new TempChangeHandler(m_Oven_TempChange);

m_Recipe = m_CookBook.GetCookieRecipe();

m_BakingPlatform =
BakingPlatformFactory.GetBakingPlatform(eBakeType. Cookie);

PreheatOven();

foreach (KeyValuePair<eRecipeItems, intitem in m_Recipe.RecipeCollection)

{

for (int i = 0; i <= item.Value; i++)

{

EventMonitor.BroadcastEvent(string.Format("Baker is adding ingredient
{0}...", item.Key.ToString()));

m_MixingBowl.AddIngredient(IngredientFactory.GetIn gredient(item.Key));

}

}

MixIngredients();

}

private void m_Oven_TempChange(object sender, int temp)

{

EventMonitor.BroadcastEvent(string.Format("Oven is reporting a temperature
of {0} degrees...", temp));

}

private delegate void MixIngredientsDelegate();

private delegate void PreheatOvenDelegate();

private void MixIngredients()

{

EventMonitor.BroadcastEvent("Baker is mixing ingredients...");

MixIngredientsDelegate sampleDelegate = new
MixIngredientsDelegate(MixIngredientsHandler);

IAsyncResult aResult = sampleDelegate.BeginInvoke(null, null);

aResult.AsyncWaitHandle.WaitOne();

sampleDelegate.EndInvoke(aResult);

bDoneMixing = true;

if (bOvenPreheated == true)

{

PutBakingPlatformInOven();

}

}

private void MixIngredientsHandler()

{

m_MixingBowl.MixIngredients();

}

private void PreheatOven()

{

EventMonitor.BroadcastEvent("Baker is preheating the oven...");

MixIngredientsDelegate sampleDelegate = new
MixIngredientsDelegate(PreheatOvenHandler);

IAsyncResult aResult = sampleDelegate.BeginInvoke(null, null);

aResult.AsyncWaitHandle.WaitOne();

sampleDelegate.EndInvoke(aResult);

bOvenPreheated = true;

EventMonitor.BroadcastEvent("Baker has been alerted that the oven is
preheated...");

if (bDoneMixing == true)

{

PutBakingPlatformInOven();

}

}

private void PreheatOvenHandler()

{

m_Oven.Preheat(m_Recipe.CookTemperature);

}

private void PutBakingPlatformInOven()

{

m_Oven.Bake(m_Recipe.CookTime);

}

private void OnDoneCooking(object sender, EventArgs e)

{

EventMonitor.BroadcastEvent("Baker is removing Baked Goods from Oven...");

m_BakedGoods = new BakedGoods(m_Recipe.BakeType);

EventMonitor.BroadcastEvent("Baker is placing baked goods onto the serving
tray...");

for (int i = 0; i <= m_Recipe.Yields; i++)

{

m_BakedGoods.AddBakedGood(BakedGoodFactory.GetBake dGood(m_Recipe.BakeType));

}

ServeBakedGoods();

}

protected virtual void ServeBakedGoods()

{

if (Served != null)

{

BakedGoodEventArgs eventargs = new BakedGoodEventArgs();

eventargs.Count = m_Recipe.Yields;

eventargs.Type = m_Recipe.BakeType;

Served(null, eventargs);

}

}

public void BakeCake()

{

}

}

//Oven class

public class Oven

{

private int m_BakingTemp = 0;

private int m_CurrentTemp = 0;

public event TempChangeHandler TempChange;

public event PreheatedHandler Preheated;

public event FinishedCookingHandler DoneCooking;

public void Preheat(int temperature)

{

int j = 0;

m_BakingTemp = temperature;

for (int i = 0; i < m_BakingTemp; i++)

{

//System.Threading.Thread.Sleep(100);

m_CurrentTemp = i;

if (j == 10)

{

//System.Diagnostics.Debug.WriteLine(m_CurrentTemp.T oString());

OnTempChange();

j = 0;

}

j++;

}

OnPreHeated();

}

protected virtual void OnPreHeated()

{

if (Preheated != null)

{

Preheated(null, m_CurrentTemp);

}

}

protected virtual void OnTempChange()

{

if (TempChange != null)

{

TempChange(null, m_CurrentTemp);

}

}

public void Bake(int CookTime)

{

for (int i = 0; i <= CookTime; i++)

{

System.Threading.Thread.Sleep(500);

}

OnDoneCooking();

}

protected virtual void OnDoneCooking()

{

if (DoneCooking != null)

{

DoneCooking(null, null);

}

}

}









"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
On Fri, 14 Dec 2007 12:12:17 -0800, RSH <wa*************@yahoo.comwrote:
>I have an Asynchronus process that is reporting back to the UI at regular
intervals. I read several posts on how to use delegates to make this
happen. But for some reason my application just hangs, nothing being
written it just hangs. when I comment out the "Invoke(new
UpdateTextCallback(UpdateText));" it works fine.

Well, you didn't post a complete code sample. So no one can say for sure
what's going on.

But my suspicion is that even though you're using (you say) a separate
thread for the async processing, your Click event handler doesn't return
right away but instead waits for the processing to complete. With the
main GUI thread blocked, there's no way for the call to Invoke() to
complete, and thus you get a deadlock.

If you want a better answer, you need to post a concise-but-complete
sample of code that reliably demonstrates the problem.

Pete

Dec 14 '07 #3
On Fri, 14 Dec 2007 12:37:42 -0800, RSH <wa*************@yahoo.comwrote:
Okay sorry...
The code you posted is not a concise sample. "Concise" means that there
is nothing in the code that is not directly related to reproducing the
problem.

If you're having trouble understanding what is needed in your sample, you
might find Jon Skeet's article useful:
http://www.pobox.com/~skeet/csharp/complete.html While are some details
in there that I feel differently about, on the whole he describes exactly
what I mean when I write "concise-but-complete".

Also, for some reason the code is winding up posted without any
indentation. Providing a concise sample is mandatory, but it would be
nice if you could also figure out the indentation issue. It's really hard
to read the code otherwise.

Pete
Dec 14 '07 #4
And maybe more about what the problem is, not getting UI, not getting
it compiled, not getting EventMonitor.BroadcastEvent working...

Yes it is easyer to read indented code without blank rows... seen the
same problem with cut/paste in the wrong format, might try going over
notepad as in cup and paste to notepad and from there to web... all
swedish char WILL annoyngy be disorted but thats wont a problem in
this case ;)

Im grumpy, I know.. just woked up and realizing its almost monday...
again...

//CY
Dec 16 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Richard Cornford | last post by:
Anyone who has taken a look at the online FAQ today may have noticed that I have updated it. The majority of the changes are the updating of broken links and the implementation of that extensive...
3
by: Vinay | last post by:
Hello I am trying to update a Progress bar on a form. I am able to update it via using a simple clock timer, but as soon as I perform a long operation G1 (generation of a report) in a separate...
2
by: Lucas Tam | last post by:
Hello, I am trying to update a datagrid via an async call, but the datagrid shows up empty. I've checked the datatable - there are indeed rows in it... Here is my code:
0
by: Luke | last post by:
Hello All, Using the following delegate, and attempting to update the UI. There is no clear examples on how to pass multiple parameters though to the dispatcher. I keep receiving an exception...
7
by: John J. Hughes II | last post by:
I have a DataGridView with a TextBoxColumn. I setting the data source to a List<stringvalue in a static class. The list is filled from a background thread. So far all is fine and it works...
8
by: =?Utf-8?B?R3JlZyBMYXJzZW4=?= | last post by:
I'm trying to figure out how to modify a panel (panel1) from a backgroundworker thread. But can't get the panel to show the new controls added by the backgroundwork task. Here is my code. In...
8
by: Justin Rich | last post by:
So another simple question from me :) as im working away ive made a button that does a series of wonderful things.. and as it goes along it suppose to update a label to let the user know what...
0
by: twoSeven | last post by:
hi, Here is what i want to do. I am making a file and folder browser similar to Windows Explorer with a treeview and listview.. In that, i get icons and thumbnails of a particular file/folder from...
7
by: =?Utf-8?B?Sm9lIFRob21wc29u?= | last post by:
Hi, I have a C# windows form application (.NET 2.0) that reads data over the serial port and displays the data via textboxes. I get a message 50 times/second. I know I can't update the screen...
2
by: Curious | last post by:
I have two classes: BulkProcessing.cs BulkProcessingStatusForm.cs BulkProcessing uses a background worker to process each row of data. BulkProcessingStatusForm is a UI form (dialog) that...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.