473,799 Members | 3,005 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

BeginInvoke async callback

Is The following Code valid it is like a mini thread pool(a friend at
work wrote it)?
I have cut down the code a bit but kept the essential parts.
The main part that I am would like explainedis when the async callback
gets called and the the line
m_WaitCallback. EndInvoke(Async Result);
How does it know which method has ended. i.e. does the AsyncResult
identify it?? Is it accepable to have one member variable used for all
of the begininvoke calls.

Thanks for any help,
Nick

public class SerialisedWorke rQueue
{
private WaitCallback m_WaitCallback;

private Queue m_Queue;
private int m_AvailableThre ads;
private int m_ThreadsInUse;

public SerialisedWorke rQueue()
{
m_WaitCallback= new WaitCallback
(PerformWork_In ternal);
m_Queue=new Queue();
m_AvailableThre ads=5;
m_ThreadsInUse= 0;
}

public void Add(object WorkerItem)
{
m_Queue.Enqueue (WorkerItem);
if (m_ThreadsInUse <m_AvailableThr eads)
SpawnWork(null) ;
}

private void SpawnWork(IAsyn cResult AsyncResult)
{
lock(this)
{
if(AsyncResult! =null)
{
m_WaitCallback. EndInvoke(Async Result);
m_ThreadsInUse--;
}

// oWorker item will be null if the queue was empty
if(m_Queue.Coun t>0)
{
m_ThreadsInUse+ +;

//Gets the next piece of work to perform
object oWorkerItem = m_Queue.Dequeue ();
//Hooks up the callback to this method.
AsyncCallback oAsyncCallback = new AsyncCallback(t his.SpawnWork);
//Invokes the work on the threadpool
m_WaitCallback. BeginInvoke(oWo rkerItem,oAsync Callback,null);
}
}
}

private void PerformWork_Int ernal(object WorkerItem)
{
//Do Work...
}
}

Nov 17 '05 #1
7 4530
> m_WaitCallback. EndInvoke(Async Result);
How does it know which method has ended. i.e. does the AsyncResult
identify it??
Note that SpawnWork() is passed as information to the BeginInvoke() call.
That means it will be called as an event handler when the asynchronous
method is done. The parameter AsyncResult indeed identifies the method
which has ended.
Is it accepable to have one member variable used for all
of the begininvoke calls.

I think (not sure) that WaitCallback is just a delegate pointing to
PerformWork_Int ernal. It would be OK to reuse that information, so one
member variable is ok.

Greetings,
Wessel
Nov 17 '05 #2
Nick,

This is what the last parameter (or second to last parameter) on the
call to BeginInvoke is for. It allows you to pass a state to the method
which you can retrieve from the IAsyncResult implementation passed to your
callback which allows you to identify which method you called, as well as
any other state information you would need.

You could use one member variable for all of the BeginInvoke calls, but
depending on the implementation, it might or might not be allowed (you might
have to match it up with the appropriate instance, or not).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

<ni*********@ho tmail.com> wrote in message
news:11******** **************@ g49g2000cwa.goo glegroups.com.. .
Is The following Code valid it is like a mini thread pool(a friend at
work wrote it)?
I have cut down the code a bit but kept the essential parts.
The main part that I am would like explainedis when the async callback
gets called and the the line
m_WaitCallback. EndInvoke(Async Result);
How does it know which method has ended. i.e. does the AsyncResult
identify it?? Is it accepable to have one member variable used for all
of the begininvoke calls.

Thanks for any help,
Nick

public class SerialisedWorke rQueue
{
private WaitCallback m_WaitCallback;

private Queue m_Queue;
private int m_AvailableThre ads;
private int m_ThreadsInUse;

public SerialisedWorke rQueue()
{
m_WaitCallback= new WaitCallback
(PerformWork_In ternal);
m_Queue=new Queue();
m_AvailableThre ads=5;
m_ThreadsInUse= 0;
}

public void Add(object WorkerItem)
{
m_Queue.Enqueue (WorkerItem);
if (m_ThreadsInUse <m_AvailableThr eads)
SpawnWork(null) ;
}

private void SpawnWork(IAsyn cResult AsyncResult)
{
lock(this)
{
if(AsyncResult! =null)
{
m_WaitCallback. EndInvoke(Async Result);
m_ThreadsInUse--;
}

// oWorker item will be null if the queue was empty
if(m_Queue.Coun t>0)
{
m_ThreadsInUse+ +;

//Gets the next piece of work to perform
object oWorkerItem = m_Queue.Dequeue ();
//Hooks up the callback to this method.
AsyncCallback oAsyncCallback = new AsyncCallback(t his.SpawnWork);
//Invokes the work on the threadpool
m_WaitCallback. BeginInvoke(oWo rkerItem,oAsync Callback,null);
}
}
}

private void PerformWork_Int ernal(object WorkerItem)
{
//Do Work...
}
}

Nov 17 '05 #3
Thanks for your replys, Just one more question then would I be able to
do the following:

SerialisedWorke rQueue swq = new SerialisedWorke rQueue()
swq.Add(null);
swq.Add(null);
swq.Add(null);

and expect it to *always* work OK??
Thanks again

Nov 17 '05 #4
Nick,

No, I wouldn't, because you don't have anything in the Add method that
is serializing access to the collection.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

<ni*********@ho tmail.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
Thanks for your replys, Just one more question then would I be able to
do the following:

SerialisedWorke rQueue swq = new SerialisedWorke rQueue()
swq.Add(null);
swq.Add(null);
swq.Add(null);

and expect it to *always* work OK??
Thanks again

Nov 17 '05 #5
Missed out the lock. so this would make the above question work??

public void Add(object WorkerItem)
{
lock(this)
{
m_Queue.Enqueue (WorkerItem);
if (m_ThreadsInUse <m_AvailableThr *eads)
SpawnWork(null) ;
}
}

Nov 17 '05 #6
I would think that the lock needs to be in the SpawnWork method.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

<ni*********@ho tmail.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
Missed out the lock. so this would make the above question work??

public void Add(object WorkerItem)
{
lock(this)
{
m_Queue.Enqueue (WorkerItem);
if (m_ThreadsInUse <m_AvailableThr *eads)
SpawnWork(null) ;
}
}
Nov 17 '05 #7
I would think that the lock needs to be in the SpawnWork method.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

<ni*********@ho tmail.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
Missed out the lock. so this would make the above question work??

public void Add(object WorkerItem)
{
lock(this)
{
m_Queue.Enqueue (WorkerItem);
if (m_ThreadsInUse <m_AvailableThr *eads)
SpawnWork(null) ;
}
}
Nov 17 '05 #8

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

Similar topics

1
7145
by: scott ocamb | last post by:
hello I have implemented a solution using async methods. There is one async method that can be invoked multiple times, ie there are multiple async "threads" running at a time. When these threads are complete, the call the Callback method. Each "thread" calls the same callback method. What thread does this callback method exist on? My testing indicates the
1
3138
by: Gomaw Beoyr | last post by:
When the BeginInvoke method of a delegate is called, the execution of the delegate is in another thread. (I'm not sure if an entirely new thread is created, or if a "sleeping" thread is used.) Now, is there any way to stop this execution? Suppose there are some really heavy calculations (or whatever) that needs to be performed every time indata change. Assume it takes somewhere around 10-60 seconds to do these calculations.
9
7604
by: David Sworder | last post by:
Hi, I have a form that displays data (is that vague enough for you?). The data comes in on a thread-pool thread. Since the thread pool thread is not the same as the UI thread, the callback function of my form follows the standard design pattern: if(IsDisposed){ return; }
2
8217
by: Jet Leung | last post by:
Hi All, There is a problem about asynchronism process.If I run the method by BeginInvoke() and how can I know when the method is finish? And maybe I can say when I can use EndInvoke()?
2
2772
by: Nick Palmius | last post by:
Hello, I am experimenting with async callbacks using BeginInvoke and EndInvoke, and although my code which I have shown below works, when the program stops at the end (on the ReadLine()), there are still 2 threads running if i pause the execution, even if I kow that EndInvoke has been called on the thread. This also happens in the async callback sample on msdn. Is this anything I need to wory about, because it doesn't seen too good to...
2
2531
by: Stampede | last post by:
Hi guys 'n' girls, I want to use callback methods when using BeginInvoke on some events. So far no problem, but know I thought about what could happen (if I'm not completly wrong). Lets say an event is triggerd with BeginInvoke and a callback funktion which is part of the instanze which is also holding the event. So the call looks something like this: public class MyClass {
6
3826
by: Shak | last post by:
Hi all, Three questions really: 1) The async call to the networkstream's endread() (or even endxxx() in general) blocks. Async calls are made on the threadpool - aren't we advised not to cause these to block? 2) You can connect together a binaryreader to a networkstream:
2
3815
by: Flack | last post by:
Hello, If I understand BeginInvoke correctly, when it is called your delegate is run on a thread pool thread. Now, if you supplied a callback delegate, that too is called on the same thread pool thread. My question is this: Do I ever need to check the value of InvokeRequired in my callback method before working with some GUI controls? Won't it always be required since the callback is running on a thread pool thread? I see some code...
10
4514
by: Frankie | last post by:
It appears that System.Random would provide an acceptable means through which to generate a unique value used to identify multiple/concurrent asynchronous tasks. The usage of the value under consideration here is that it is supplied to the AsyncOperationManager.CreateOperation(userSuppliedState) method... with userSuppliedState being, more or less, a taskId. In this case, the userSuppliedState {really taskId} is of the object type,...
0
9546
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
10491
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...
0
10268
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10031
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...
1
7571
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
6809
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();...
1
4146
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
2
3762
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.