Design Template for multithreading (an example here)


R

RayLopez99

Multi threading multithreading multi-threading threading threads
multitasking WaitOne .Set .Reset ManualResetEvent AutoResetEvent.

Here is a design template you can use for multithreading.

I prefer to use the manual reset event: ManualResetEvent rather than
AutoResetEvent. It forces you to Set and Reset, and IMO is better
than using the "automatic" way, which is more lazy.

The design context is as follows:

//put this mrevent outside your constructor, as a 'global' variable to
the translation unit.

public static ManualResetEvent mrevent = new ManualResetEvent
(false); //used to make thread2 wait for thread1, which it depends on
below

Thread ThreadFirst, ThreadLast; //in constructor

private void AnyfunctionHere ()
{
ThreadFirst = new Thread(new ThreadStart(Function1));

if (ThreadFirst.IsAlive == false)
{
ThreadFirst.Start();

}

ThreadLast = new Thread(new ThreadStart(Function2));
if (ThreadLast.IsAlive == false)
{

ThreadLast.Start();
}


}

private void Function1()
{
//do stuff here
mrevent.Set(); //at end, unblocks other threads
}


private void Function2()
{

bool myBoolStartThisThreadYet = false;
myBoolStartThisThreadYet = mrevent.WaitOne(); //blocks this thread
until Function1 is done

if (myBoolStartThisThreadYet != true) return;
int myInt = 123;
//do stuff here that has to happen after Function1
//if you get runtime exception for certain portion of code, put that
code below inline as shown here (you can also do the same thing in
Function 1). Keep in mind there seems to be a slight performance
penalty for doing this, but it's sometimes the only way you can make
it work:

//note format!

this.Dispatcher.BeginInvoke(delegate()
{
//put runtime exception code here. You can use variables from
Function2 here (in scope)
int j = myInt; //OK
}
);

mrevent.Reset(); //sets thread2 to block mode (opposite of set).
}


RL
 
Ad

Advertisements

R

RayLopez99

//if you get runtime exception for certain portion of code, put that
code below inline as shown here (you can also do the same thing in

Just to be clear, here is the runtime exception you sometimes get,
that you can get around using the Dispatcher:

System.UnauthorizedAccessException: Invalid cross-thread access

RL
 

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