473,383 Members | 1,863 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,383 software developers and data experts.

Help with multithreading and state in a scientific simualtion program

Im writing a program that does monte carlo simulation and im having
trouble figuring out how to get the threading model right. I have a
simulation class which contains all simulation data and methods to run
the simulation for an x number of sweeps. An instance of this object is
declared in the class of my main form. The main form handles graphics
(it shows the particles moving on the form). I am now trying to split
up the work so that the UI thread is separate from the thread running
the simulation prgoram. I will also probably be adding a form to
allowing viewing of the same data by chart, so i need the simualtion
object to be accessible from multiple forms. The simulation object has
an event which is triggered when the simulation moves a particle, with
the form listening for that event and updating itself. The problem is
when i run the simulation in a separate thread i get exceptions when
trying to access graphics objects for drawing (because im accessing UI
elements from a nonUI thread).

Can someone help me out to figure out a good structure for the program?

Nov 17 '05 #1
13 1411
To draw you'll have to invoke calls on the thread that created the form (or control your drawing to).

Control.InovkeRequired will let you know if the code is executing on a non-ui thread
Control.Invoke(new MethodInvoker(ParameterlessMethod)) will invoke a method on the ui-thread where you should place your drawing
code:

if (ctrl.InvokeRequired)
ctrl.Invoke(new MethodInvoker(DoDraw));
else
DoDraw();

--
Dave Sexton
dave@www..jwaonline..com
-----------------------------------------------------------------------
<mg******@gmail.com> wrote in message news:11**********************@g49g2000cwa.googlegr oups.com...
Im writing a program that does monte carlo simulation and im having
trouble figuring out how to get the threading model right. I have a
simulation class which contains all simulation data and methods to run
the simulation for an x number of sweeps. An instance of this object is
declared in the class of my main form. The main form handles graphics
(it shows the particles moving on the form). I am now trying to split
up the work so that the UI thread is separate from the thread running
the simulation prgoram. I will also probably be adding a form to
allowing viewing of the same data by chart, so i need the simualtion
object to be accessible from multiple forms. The simulation object has
an event which is triggered when the simulation moves a particle, with
the form listening for that event and updating itself. The problem is
when i run the simulation in a separate thread i get exceptions when
trying to access graphics objects for drawing (because im accessing UI
elements from a nonUI thread).

Can someone help me out to figure out a good structure for the program?

Nov 17 '05 #2
if figured that much out. the problem is my simulation object does not
have access to the form it is running in, so it cant use invoke. Also
.... im noticingf something strange and id like an explanation ... for
some reason if i run Invalidate() in the form while running on the
nonui thread, the form_paint executes in the ui thread by itself. how
does this happen and why?

Nov 17 '05 #3
WinForms controls use the message loop. The paint message is sent to itself when you invoke Invalidate(). The message is received
on the ui thread, and the rest is history.

I suggest adding a parameter to your simulation object's constructor:

public Simulator(Form owner)
{
this.owner = owner;
}

If you need multiple forms to access the object, a Singleton pattern might be what your after:

public class Simulator
{
// thread-safe singleton pattern implementation
public static readonly Simulator Instance = new Simulator();

// disallow construction of the object from external classes
private Simulator() {}

public void Run(Form owner)
{
// Todo: start a new thread and run the simulation on the specified form (owner)
}

[...]

Simulator.Instance.Run(this); // this, is a Form reference

You can expose events that your form classes can listen to on the instance.

--
Dave Sexton
dave@www..jwaonline..com
-----------------------------------------------------------------------
"Michael Gorbach" <mg******@gmail.com> wrote in message news:11**********************@o13g2000cwo.googlegr oups.com...
if figured that much out. the problem is my simulation object does not
have access to the form it is running in, so it cant use invoke. Also
... im noticingf something strange and id like an explanation ... for
some reason if i run Invalidate() in the form while running on the
nonui thread, the form_paint executes in the ui thread by itself. how
does this happen and why?

Nov 17 '05 #4
Thanks for the help Dave.
I think the singelton might just be what im looking for.
Heres more details on the way im trying to rewrite the program:
I have a main form which controls how many sweeps and tells the
simulation to run.
I have a graphics form which displays the molecules, instantiated as an
object inside the mainform.
I have a table form which displays the simulation as a table of
particles, also instantiated inside the mainform.
I need to have only one simulation in the entire program at once, and i
need both viewer forms to be able to access it, and the main form to be
able to tell it to run. I want the simulation running in a separate
thread from the GUI. The thing to note is that there will be no outside
changing to the simulation object after it is instantiated, its
members need only be "read" by the viewers.
I feel like there should be only global instance of simulation that all
three forms can access ... is singelton what i need?

Nov 17 '05 #5
Absolutely. The pattern is for classes that need to be instantiated, like other non-static classes, except with one different
criteria; The class must only be instantiated once.

By providing the "private" constructor you are ensuring that the class will not be instatiated (without the use of reflection) by
calling code except for the single "Instance" that is created automattically by the class itself.

In the example I gave you, it can be viewed that the Run method provides construction logic for the component. All other
properties/fields should probably be private, readonly or properties with only "get" accessors. This will ensure that calling code
may not modify any instance fields after the singleton is instantiated. (You can use the "Run" method, or whatever you'd like to
call it, to provide a means for state-settings.)

Applied, your "controller" form can call "Run" on the "Instance" with any state-setting parameter's you'd like to include. Your
"charting" form can listen to public instance events that you may declare or just access public read-only properties at runtime.
The same would go for your "tabular" form.

GL

--
Dave Sexton
dave@www..jwaonline..com
-----------------------------------------------------------------------
"Michael Gorbach" <mg******@gmail.com> wrote in message news:11**********************@g43g2000cwa.googlegr oups.com...
Thanks for the help Dave.
I think the singelton might just be what im looking for.
Heres more details on the way im trying to rewrite the program:
I have a main form which controls how many sweeps and tells the
simulation to run.
I have a graphics form which displays the molecules, instantiated as an
object inside the mainform.
I have a table form which displays the simulation as a table of
particles, also instantiated inside the mainform.
I need to have only one simulation in the entire program at once, and i
need both viewer forms to be able to access it, and the main form to be
able to tell it to run. I want the simulation running in a separate
thread from the GUI. The thing to note is that there will be no outside
changing to the simulation object after it is instantiated, its
members need only be "read" by the viewers.
I feel like there should be only global instance of simulation that all
three forms can access ... is singelton what i need?

Nov 17 '05 #6
one more question ... my simulation triggers events that are listened
to by the charting form, but it seems that the methods wired to those
events (in the charting form) are executing in the simulation thread
and not in the forms gui thread. Why, and how do i fix this? I cant
have forms listening to events from the simulation object if in the
eventhandlers i cant manipualte the GUI ...

Nov 17 '05 #7
Michael Gorbach <mg******@gmail.com> wrote:
one more question ... my simulation triggers events that are listened
to by the charting form, but it seems that the methods wired to those
events (in the charting form) are executing in the simulation thread
and not in the forms gui thread. Why, and how do i fix this? I cant
have forms listening to events from the simulation object if in the
eventhandlers i cant manipualte the GUI ...


Event handling delegates are always executed on the thread that raises
the event. You need to call Control.Invoke/BeginInvoke within the event
handler to get back to the UI thread.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #8
right ... thats what iv understood from my reading. what i dont
understand is ... why does the invalidate event behave differently from
the cuustom event that i created? When i raise the invalidate event it
executes in the GUI thread, when i raise my event the handling method
is called in the simulation thread.

Nov 17 '05 #9
Michael Gorbach <mg******@gmail.com> wrote:
right ... thats what iv understood from my reading. what i dont
understand is ... why does the invalidate event behave differently from
the cuustom event that i created? When i raise the invalidate event it
executes in the GUI thread, when i raise my event the handling method
is called in the simulation thread.


Where and how are you raising the invalidate event? My guess is that
you're either raising it in the UI thread, or that the method you call
to raise it is *actually* calling Invoke/BeginInvoke to raise it in the
UI thread.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #10
my simulation fires an event when a move is accepted (the simulation is
changed). This event is caught by the charting form in a handler. If i
run invokerequired in the handler, it returns true. The handler runs
this.invalidate(); When i run invokerequired in the invalidate method,
it returns false. It is almost as if something is doing an implied
invoke.

Nov 17 '05 #11
Michael Gorbach <mg******@gmail.com> wrote:
my simulation fires an event when a move is accepted (the simulation is
changed). This event is caught by the charting form in a handler. If i
run invokerequired in the handler, it returns true. The handler runs
this.invalidate(); When i run invokerequired in the invalidate method,
it returns false. It is almost as if something is doing an implied
invoke.


Could you post a short but complete program which demonstrates this?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #12
Mr Skeet,

In a previous post I mentioned that the Invalidate method is sending a windows message to the control/form that is being
invalidated. A paint message is then received by the WndProc procedure running on the UI Thread.

Isn't this correct?

--
Dave Sexton
dave@www..jwaonline..com
-----------------------------------------------------------------------
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message news:MP************************@msnews.microsoft.c om...
Michael Gorbach <mg******@gmail.com> wrote:
my simulation fires an event when a move is accepted (the simulation is
changed). This event is caught by the charting form in a handler. If i
run invokerequired in the handler, it returns true. The handler runs
this.invalidate(); When i run invokerequired in the invalidate method,
it returns false. It is almost as if something is doing an implied
invoke.


Could you post a short but complete program which demonstrates this?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #13
Dave <NO*********@dotcomdatasolutions.com> wrote:
In a previous post I mentioned that the Invalidate method is sending
a windows message to the control/form that is being invalidated. A
paint message is then received by the WndProc procedure running on
the UI Thread.

Isn't this correct?


I'm not sure, but Invalidate shouldn't be called on a non-UI thread as
far as I know.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #14

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

Similar topics

10
by: gianguz | last post by:
The question is about the possible use of inlining to improve performance in a heavy multithreading environment (200+ threads). If we have to work with applications in which threads aren't I/O...
1
by: Nick | last post by:
Well, the project I am working on has now come to a screeching halt! I have been developing a program that heavily utilizes ADO.NET record sets. To generate reports, I convert the recordset to XML,...
16
by: Robert Zurer | last post by:
Can anyone suggest the best book or part of a book on this subject. I'm looking for an in-depth treatment with examples in C# TIA Robert Zurer robert@zurer.com
9
by: Popoxinhxan | last post by:
Dear experts, i want to develop an client application that consume the google search web service. In my MainForm i have a method to retrieve all the search result e.g. GetGoogleResults(). Now i...
5
by: sarge | last post by:
I would like to know how to perform simple multithreading. I had created a simple form to test out if I was multithreading properly, but got buggy results. Sometime the whole thig would lock up...
16
by: who be dat? | last post by:
Consider the following code which enables multithreading in an ASP.Net application I'm writing: Code in global.asx Application_start subroutine, Threadnotify is declared Globally as a new thread...
1
by: robinsand | last post by:
I am a new C++ programmer. I am still having trouble with certain data types and constructors, among other things. I'm not sure if I've used "std::string" properly throughout this program. I need...
20
by: S.Mohideen | last post by:
Hi Folks, Python is praised about - me too. But at one instance it fails. It fails to behave as a true multi-threaded application. That means utilizing all the CPUs parallely in the SMP...
15
by: colemanj4 | last post by:
Here is what I have so far, it loops while the PW is incorrect, or until cancel is selected. I want it to lock the tables for adds, deletes, and edits when cancel is selected, and if the PW is...
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
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.