473,657 Members | 2,496 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Re: thread communication

Thanks Chris,
Looks nice but I miss the dual way communication. In the main thread to
deliver paramters and data to the worker thread- how can I do that?
Regards
Ronny
Take a look at the background worker thread component. It has what
you want built into it.

http://msdn.microsoft.com/en-us/library/8xs8549b.aspx

Chris
Oct 13 '08 #1
12 2074
On Mon, 13 Oct 2008 10:19:08 -0700, Ronny <ro***@john.com wrote:
Thanks Chris,
Looks nice but I miss the dual way communication. In the main thread to
deliver paramters and data to the worker thread- how can I do that?
It really depends on the exact data, what the thread will do with it, and
how you want the data to be delivered.

The simplest approach is to pass all the data to the thread when you start
it up. The BackgroundWorke r class supports this easily. To pass data to
a thread as it's executing means you need to come up with a specific
strategy of what data is being passed, when the thread will retrieve it,
and how. One possible approach is to use a queue that the worker thread
reads from while other threads write to (see "producer/consumer" in
Google). But that's hardly the only approach one might take, nor is it
universally the most appropriate.

Unless you can provide a more specific question, it's going to be very
difficult to provide any sort of answer to your question.

Pete
Oct 13 '08 #2
Thanks Mr. Pete,
In my scenario the main thread should pass to the worker thread some string
from time to time. In C++ programming I would use global data as the
simplest mechanism (though not so elegant)but in C# I guise its forbidden.
Can you farther help?
Regards
Ronny
"Peter Duniho" <Np*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local. ..
On Mon, 13 Oct 2008 10:19:08 -0700, Ronny <ro***@john.com wrote:
>Thanks Chris,
Looks nice but I miss the dual way communication. In the main thread to
deliver paramters and data to the worker thread- how can I do that?

It really depends on the exact data, what the thread will do with it, and
how you want the data to be delivered.

The simplest approach is to pass all the data to the thread when you start
it up. The BackgroundWorke r class supports this easily. To pass data to
a thread as it's executing means you need to come up with a specific
strategy of what data is being passed, when the thread will retrieve it,
and how. One possible approach is to use a queue that the worker thread
reads from while other threads write to (see "producer/consumer" in
Google). But that's hardly the only approach one might take, nor is it
universally the most appropriate.

Unless you can provide a more specific question, it's going to be very
difficult to provide any sort of answer to your question.

Pete

Oct 13 '08 #3
You could quite easily create a class which has

A: A queue<string>
B: A worker thread
C: An object you use to lock()

When you want to add data you call a public method which does

lock(SyncRoot)
Queue.Enqueue(d ata);
When the thread wants data

string data = null;
string hasData = false;
lock(SyncRoot)
{
hasData = Queue.Count 0;
if (hasData)
data = Queue.Dequeue() ;
}

//Process "data"

You can either make the thread sleep, or you can use an AutoResetEvent that
the thread waits for, and call AutoResetEvent. Set() from your public method
which enqueues.

--
Pete
====
http://mrpmorris.blogspot.com
http://www.capableobjects.com

Oct 13 '08 #4
On Mon, 13 Oct 2008 14:07:24 -0700, Peter Morris
<mr*********@sp amgmail.comwrot e:
[...]
You can either make the thread sleep, or you can use an AutoResetEvent
that the thread waits for, and call AutoResetEvent. Set() from your
public method which enqueues.
Though, IMHO for this pattern, using the Monitor class is more idiomatic
for C#/.NET. The consumer thread can just call Monitor.Wait() from within
the lock, while the producer thread will call Monitor.Pulse() when new
data is added to the queue.

Of course, all of the preceding (Peter M.'s pseudocode as well as my
elaboration) assumes a worker thread that _only_ processes data sent to it
via the queue. IME, this is a very common scenario, but if you the
original poster have a thread that is doing other work as well, you will
have to figure out how to decide if and when to check the queue for new
data.

To the OP, re: your previous comment about "In C++ programming I would use
global data as the simplest mechanism (though not so elegant)but in C# I
guise its forbidden", while it's true there's not really any such thing as
global data in C#, if you really wanted to, you could implement a solution
that uses practically the same technique, simply by using a variable
within a class to hold the data.

In fact, to some extent, that's what the queue does, just in a more
flexible way (it can hold more than one item at a time). The variable can
be a static member of a class, making it _very_ similar to your global
variable in C++, or it can be an instance member of a class, allowing you
to implement the functionality in a way that provides for multiple
instances of the class to be operating independently simultaneously.

I do think that a queue would be more elegant than a single variable, but
if you know you only ever have one piece of data to transfer at a time,
the queue is overkill. :)

Pete
Oct 13 '08 #5
Hi Pete

http://msdn.microsoft.com/en-us/libr...tor.pulse.aspx

I don't know if it's just too early in the morning or what, but this doesn't
make sense to me :-)
public void FirstThread()
{
int counter = 0;
lock(m_smplQueu e)
{
while(counter < MAX_LOOP_TIME)
{
// Release the lock and then regain it, so why lock in
the first place?
Monitor.Wait(m_ smplQueue);
//Push one element.
m_smplQueue.Enq ueue(counter);

//Let some other thread lock it?
Monitor.Pulse(m _smplQueue);

counter++;
}
}
}
public void SecondThread()
{
lock(m_smplQueu e)
{
//Release the waiting thread.
Monitor.Pulse(m _smplQueue);
//Wait in the loop, while the queue is busy.
//Exit on the time-out when the first thread stops.
while(Monitor.W ait(m_smplQueue ,1000))
{
//Pop the first element.
int counter = (int)m_smplQueu e.Dequeue();
//Print the first element.
Console.WriteLi ne(counter.ToSt ring());
//Release the waiting thread.
Monitor.Pulse(m _smplQueue);
}
}
}
Nah, it means nothing to me. The way it is explained just doesn't fit into
my brain, I suspect I have a misunderstandin g of something else somewhere
which prevents it from making sense. Would you have time to explain it to
me please?
--
Pete
====
http://mrpmorris.blogspot.com
http://www.capableobjects.com

Oct 14 '08 #6
On Tue, 14 Oct 2008 00:39:37 -0700, Peter Morris
<mr*********@sp amgmail.comwrot e:
[...]
Nah, it means nothing to me. The way it is explained just doesn't fit
into my brain, I suspect I have a misunderstandin g of something else
somewhere which prevents it from making sense. Would you have time to
explain it to me please?
I'm not sure what it is about Microsoft tech writers that motivate them to
write samples like that. I've seen similar stuff elsewhere (for example,
the sample for the Interlocked class), where they take what should be a
simple concept and make up some complicated, contrived example.

Anyway, that's a long way of saying that the MSDN sample is unnecessarily
confusing. I'm not surprised it didn't help you. I'm not sure how it'd
help anyone who didn't already know how to use the class.

A more typical use of the Monitor class would be to have one thread using
Wait() and the other using Pulse(). For example (warning: more uncompiled
code ahead :) ):

object _objLock = new object();
Queue<object_qu eue = new Queue<object>() ;

void ProcessLoop()
{
lock (_objLock)
{
while (true)
{
if (_queue.Count 0)
{
object obj = _queue.Dequeue( );

// process "obj" somehow
}
else
{
Monitor.Wait(_o bjLock);
}
}
}
}

void AddWork(object obj)
{
lock (_objLock)
{
_queue.Enqueue( obj);
Monitor.Pulse(_ objLock);
}
}

Basically:

-- for both Wait() and Pulse(), the calling thread must already own
the lock
-- Wait() will _release_ the lock and suspend the thread until some
other thread calls Pulse(); the suspended thread is moved into a wait
queue for the lock
-- Pulse() will release _a_ thread waiting on the lock, by moving it
into a ready queue for the lock; when the calling thread releases the
actual lock, then the released thread will then acquire the lock and be
able to run when it's next scheduled

Note that multiple threads could actually be waiting on the lock. Pulse()
just picks the first one in the wait queue and moves it to the ready
queue. Likewise, when a thread releases the lock, the first one in the
ready queue is the one that acquires the lock next. If you have only one
consumer thread, then obviously that thread is always the one that gets to
resume when Pulse() is called.

The doc pages for those methods have various comments and caveats. The
Monitor class isn't _always_ the right approach, but it does fit into the
producer/consumer scenario very well, and is very useful in other patterns
too.

Pete
Oct 14 '08 #7
Hi Pete
Anyway, that's a long way of saying that the MSDN sample is unnecessarily
confusing. I'm not surprised it didn't help you. I'm not sure how it'd
help anyone who didn't already know how to use the class.
I am glad, because as I read it I had no idea what it was trying to teach me
:-)

void ProcessLoop()
<snip>
void AddWork(object obj)
<snip>

Now that example I looked at and understood immediately :-)

In summary

Monitor.Wait(Sy ncRoot);
will do this
01: Release the lock
02: Suspend the thread until Monitor.Pulse(S yncRoot) is called

Monitor.Pulse(S yncRoot);
will do this
01: Release the lock
02: Awaken any threads suspended using Monitor.Wait(Sy ncRoot)

I presume it is a mistake to do this...

Monitor.Wait(Sy ncRoot);
//Some other code here that depends on the lock being held

and finally, if this were a service and I wanted to let the worker thread
die I would send a Pulse to wake it up so that it had the opportunity to
check that the service has been stopped?

An excellent example, MSDN should be updated :-) I really appreciate you
spending your time explaining this to me, thanks!

--
Pete
====
http://mrpmorris.blogspot.com
http://www.capableobjects.com

Oct 14 '08 #8
On Tue, 14 Oct 2008 04:02:25 -0700, Peter Morris
<mr*********@sp amgmail.comwrot e:
[...]
In summary

Monitor.Wait(Sy ncRoot);
will do this
01: Release the lock
02: Suspend the thread until Monitor.Pulse(S yncRoot) is called

Monitor.Pulse(S yncRoot);
will do this
01: Release the lock
02: Awaken any threads suspended using Monitor.Wait(Sy ncRoot)
Not quite. Calling Pulse() doesn't release the lock. Exiting the lock()
statement or calling Monitor.Leave() does (they are equivalent). So all
that calling Pulse() does is your "02" item, and only in the sense that a
suspended thread gets moved into the ready queue for the Monitor object.
That thread still won't be runnable until two conditions are met: 1) it's
the first thread in the ready queue, and 2) no other thread still has the
lock.

The first condition might wind up being met as a direct result of Pulse()
being called, but the second can't be met until the thread that called
Pulse() releases the lock.
I presume it is a mistake to do this...

Monitor.Wait(Sy ncRoot);
//Some other code here that depends on the lock being held
Nope, that's fine (and in fact, the code I posted does basically
that...see the while(true) loop). In particular, the Wait() method may
not be called unless the calling thread has acquired the lock. And when
Wait() returns, the calling thread will have re-acquired the lock (having
released it while it was waiting).
and finally, if this were a service and I wanted to let the worker
thread die I would send a Pulse to wake it up so that it had the
opportunity to check that the service has been stopped?
Yes. For example, if you had a queue managed by the code I posted, one
strategy for telling the code to exit the while(true) loop would be to
enqueue a special sentinel value that signals the ProcessLoop() method to
break out of the loop.
An excellent example, MSDN should be updated :-) I really appreciate
you spending your time explaining this to me, thanks!
No problem, happy to help. :)

Pete
Oct 14 '08 #9
Not quite. Calling Pulse() doesn't release the lock. Exiting the lock()
statement does
Ah yes ofcourse. I was remembering the code rather than reading it. The
Pulse() isn't in a loop, so after sending Pulse() it drops out of the lock.

>I presume it is a mistake to do this...

Monitor.Wait(Sy ncRoot);
//Some other code here that depends on the lock being held

Nope,
Glad I asked. Although Monitor.Wait() releases the lock the thread isn't
resumed until 2 conditions are met.
01: Pulse
02: It re-acquires the lock

Excellent. Very well taught :-)

I will post feedback on the MSDN article with a link to your source.

Thanks again!
--
Pete
====
http://mrpmorris.blogspot.com
http://www.capableobjects.com

Oct 14 '08 #10

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

Similar topics

3
2211
by: David Sworder | last post by:
This message was already cross-posted to C# and ADO.NET, but I forgot to post to this "general" group... sorry about that. It just occured to me after my first post that the "general" group readers might have some thoughts on this perplexing .NET blocking issue. (see below) ===== Hi,
1
1641
by: Ayende Rahien | last post by:
Is it possible to use events as a communication mechanism between threads?
7
9440
by: Brett Robichaud | last post by:
I'm trying to decide on the right approach for communication between the UI and a worker thread in a WinForms app. I am very familiar with threads in the unmanaged C++ world and in the past have used WM_USER based messages to communicate status from the worker thread back to the UI thread. What is the right way to do this in .Net? Are asynchronous delegates the way to go, or is there a better (or just different) approach I should...
9
3068
by: mareal | last post by:
I have noticed how the thread I created just stops running. I have added several exceptions to the thread System.Threading.SynchronizationLockException System.Threading.ThreadAbortException System.Threading.ThreadInterruptedException System.Threading.ThreadStateException to see if I could get more information about why the thread stops running but that code is never executed. Any ideas on how I can debug this?
20
2392
by: Bob Day | last post by:
Using VS 2003, VB, MSDE... There are two threads, A & B, that continously run and are started by Sub Main. They instantiationsl of identical code. Thread A handles call activity on telephone line 1 and Thread B handles call activity on telephone line 2. They use a common SQL datasource, but all DataSets are unique to each thread. Is there a way for thread A to occasionally communication to thread B that something has happened? ...
1
2520
by: Fred B | last post by:
I am launching a new thread from my application's main process (using VB.net 2003), and I can't get the child to receive the parameter I'm attempting to send it in a named data slot. The code for launching the thread: Dim NewThread As New Thread(AddressOf LaunchCommThread) NewThread.AllocateNamedDataSlot("Offset") NewThread.IsBackground = True NewThread.Name = SIMclass.SIM(1).strCtrlDesignator
2
2318
by: Max | last post by:
Hello, I made an application that uses the main thread for the UI, and another thread to communicate through the RS232 port. I would like the communication thread to be suspended immediately when the user presses the ESC key. It should resume when the user answers a dialog box. The Thread.Suspend cannot be used anymore in .NET and I'm trying to figure out how to do this differently. Can anyone help? Cheers, Max.
6
5117
by: HolyShea | last post by:
All, Not sure if this is possible or not - I've created a class which performs an asynchronous operation and provides notification when the operation is complete. I'd like the notification to be performed on the same thread thread that instantiated the class. One way to do this is to pass an ISynchronizeInvoke into the class and use it to synchronize the callback. In the constructor of the class, could I take note of the current thread...
1
2045
by: NagarajanS | last post by:
hi, i have a problem in cross thread communication.my problem is i drog some controls in the form.now i created new thread inside the coding of form.cs.when i try to run that thread it shows the "cross thread communication".is any possible to send the user control objects to the new thread?or what i have to eliminate this error. regards nags
0
8326
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8845
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8522
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8622
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7355
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6177
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5647
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4333
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2745
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.