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

Home Posts Topics Members FAQ

Using EndInvoke From within an AsyncCallback?

I've been working on some samples that use BeginInvoke/EndInvoke. In one
example, I call BeginInvoke and pass it an AsyncCallback function pointer.
I was messing around with ReaderWriterLoc ks and noticed that if I did this,
it worked (please ignore the lack of try ... catch blocks, because I cut
down the code to be more brief - I have a try...catch surround the
AcquireWriterLo ck method):
----------
myLock.AcquireW riterLock(1000) ;
iasResult = fprUIUpdate.Beg inInvoke(strBuf fer,null,null);

// Some other async operations can be done here

// Get the results of the delegate using EndInvoke. This will block
// execution of this thread until the delegate invoked completes
fprUIUpdate.End Invoke(iasResul t);
myLock.ReleaseW riterLock();
---------
But, if I do it this way, the WriterLock never gets cleared, even though the
statement gets executed in the AsyncCallback method:
---------
myLock.AcquireW riterLock(1000) ;
iasResult = fprUIUpdate.Beg inInvoke(strBuf fer,new
AsyncCallback(M essageUpdatedCa llBack),null);

// Some other async operations can be done here

public void MessageUpdatedC allBack(System. IAsyncResult Result)
{
// Get the results of the delegate using EndInvoke
fprUIUpdate.End Invoke(iasResul t);

// Operation completed, we can now give up the buffer lock
myLock.ReleaseW riterLock();
}
---------

I've validated that the myLock.ReleaseW riterLock method gets called in the
AsyncCallback routine, but for some reason the very next time it gets
checked, it comes back as locked. BUT, if I move it all back into the
thread and don't use callbacks, the same logic seems to work fine.

Is myLock no longer the same object reference (even though it's all in the
same class) because it's now inside an AsyncCallback function? I made
myLock a static variable inside the class to make sure that this wasn't the
problem, but no luck.

--
Doug Thews
Director, Customer Solutions
D&D Consulting Services
----------------
Visit my Tech Blog at:
http://www.ddconsult.com/blogs/illuminati/
Nov 16 '05
11 3790
I'll give you some examples off the top of my head of articles/books that
discuss threading, but with a Console-only approach, and never talk about
updating the UI safely via a worker thread and a lot of them use
Thread.Abort() without talking about the stuff you have mentioned (BTW ...
the article links just happen to be the highest rated on Google under "C#
AND Threading" - another problem for developers):

Books:
VB.NET Threading Handbook
C# Threading Handbook

Articles:
http://www.codeproject.com/csharp/threader.asp
http://www.dotnetjunkies.com/Tutoria...CF766EC8E.dcik
http://msdn.microsoft.com/library/de...ngtutorial.asp
(an MSDN article with Thread.Abort() in it)
http://builder.com.com/5100-6373-104...ml#Listing%20A (supposedly a
beginner's article, but all Console and not much help).

These are just a sample of article links found on Google under "C# AND
Threading", but they happen to be the highest rated. None of them cover
what you've discussed, and the only one that comes close is an article
written by Chris Sells (that shows up on the 4th page of the Google search),
that finally talks about delegates and synchronization .

As you can see, each one of them uses Thread.Abort() (even the MSDN
article), so you can see where my idea of getting a mainstream article out
there for beginners in print comes from (maybe I'll do one for VSM). You
can also see that every one of these uses a simple Console app with no use
of external class methods containing the threadstart pointer, but that gives
a WinForms or ASP.NET developer no clue how to extend that to their
platform. As you already know, there are a lot more things to get straight
when taking threads to WinForms or ASP.NET - and THAT is what needs to get
out.

Thanks a bunch for all your tips. Please save my e-mail & blog info as I'd
like to keep in touch in the future.

--
Doug Thews
Director, Customer Solutions
D&D Consulting Services
----------------
Visit my Tech Blog at:
http://www.ddconsult.com/blogs/illuminati/

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Doug Thews <do*******@remo veme.ddconsult. com> wrote:
Hey, thanks for the link. So, the AsyncCallback method runs in another
thread in the thread pool, and not in the same thread as the actual
worker
thread that's running, right?


I think it's *likely* to run in the same thread that the delegate runs
in. It won't be running in the thread which calls BeginInvoke.
That's why putting a lock in the
AsyncCallback method doesn't work, because THAT thread doesn't have a
lock
(the other worker thread does - so that's why an exception is generated
in
the AsyncCallback method). Do I have it right?


Yup.
BTW ... I think it's a good idea to write an article from a beginner's
perspective, and I plan to do so - thanks to your help. What I've found
is
that there are a lot of thread articles out there, and NONE OF THEM talk
about the dangers of Thread.Abort()


That's a definite "TBD" in my own article at the moment.
how to safely update the UI (because
most of them just are console test apps - pretty worthless), and none of
them talk about using delegates off of instantiated objects (all of the
examples I've seen, just put the thread code into the Main or Form
class -
again, not realistic).


Actually, almost *all* threading articles that I've seen talk about how
to safely update the UI. They do tend to usee delegates in the form
rather than existing class, but I think that's a more "general C#
understanding" than threading issue. I'll change some of my examples to
use delegates in another class though.

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

Nov 16 '05 #11
Doug Thews <do*******@remo veme.ddconsult. com> wrote:
I'll give you some examples off the top of my head of articles/books that
discuss threading, but with a Console-only approach, and never talk about
updating the UI safely via a worker thread and a lot of them use
Thread.Abort() without talking about the stuff you have mentioned (BTW ...
the article links just happen to be the highest rated on Google under "C#
AND Threading" - another problem for developers):


<snip>

Yup, I guess they are there after all :(

However, I *have* seen plenty of articles which talk about using Invoke
etc. I think you've been fairly unlucky, but I won't disagree that
there's a lot of misinformation around. I don't think I'd realised
quite how bad it was.

I think the business about using a different class to the original form
really is separate from threads though - anyone who understands what
delegates are (a very different topic) should naturally pick up that it
doesn't need to be in the same class. I agree it would be better to
have some examples which show that though.

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

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

Similar topics

2
2041
by: AJ | last post by:
Ok, I have a "form" class, which I am going to use to generate HTML forms. I also have a form_input, which I use to generate the individual HTML input elements. What I want to do is some how manage the instances of the form_input class, within the form class. There should be no problem with this, but I can't work out how I can store an unspecified number of instances of one
2
2169
by: Martin Lucas-Smith | last post by:
I have a class from within which other classes are called. In the constructor, I want to create an instance of a database connection, so that this database can be called elsewhere. <?php # Declare a class foo class foo { # Constructor
5
1709
by: Jim Cser | last post by:
Hello- I have a function to generate a multi-dimensional array, which then gets summed over one axis. The problem is that the dimensions are large, and I run out of memory when I create the entire array, so I'm trying to do the sum *within* the function. Example-- variables x,y,z,t; dimensions numX, numY, numZ, numT; functions f1(x,y,z,t), f2(y,z,t); want to calculate f1*f2 and sum over t to get out.
3
5136
by: Drew Richardson | last post by:
On my page, I have a stylesheet that puts a "cell" in the middle of the page then creates another frame within that cell. I have my external links below the middle frame, so that only my content scrolls. My question is, can I put a link outside of the content div class that will load into the content frame? My stylesheet code is below if it helps... div.textbox { background-color: #000000; font-family: verdana;
2
974
by: John | last post by:
Hi all, Am I allowed to use labe;s within the datagrid heading section? Each time I drag a label onto the design, I can set the properties and such (including runat=server) but the code-behind refuses to accept/acknowledge it's existence. Am I just doing something wrong and if so, what? Regards
1
1874
by: Tor Inge Rislaa | last post by:
Using PowerPoint within my application I am developing an application that needs some functionality of displaying some text and graphic in full screen modus, as when you run a PowerPoint show. Is there a way that I can use the functionality of PowerPoint within my application, an ActiveX for instance? What I want is to dynamically create the number of slides I need, add textboxes to the slides and run the show. I need for an object that...
0
975
by: Michael B. Trausch | last post by:
Hello, everyone. I am doing some searching and winding up a little bit confused. I have a MUD client that I am writing using Python and wxWidgets, as some of you may remember. What I am looking to do now, is add "trigger" functionality to it. In essence, the application receives text from the game, and if it is in any of the trigger definitions, it acts on it by executing Python code that the user has associated with the action. ...
3
8245
by: duyanning | last post by:
I have written a pyhton script that will process data file in current working directory. My script is in an different directory to data file. When I debug this script using pdb within emacs, emacs will change the current working directory to the directory which include the script, so my script cannot find the data file. I think this is the problem of emacs because when I start pdb from console directly, it will not change current...
3
2272
by: Ilyas | last post by:
Hi all What is the recommended way for using Linq within a 3 Tier project? Many thanks
0
10490
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
10260
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
10030
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
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();...
0
5467
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5590
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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.