turbopowerdmaxsteel
Feb 22 2007, 11:42 AM
I have a class named as test which triggers an event using the Timer class, the code for which is given below. CODE using System; using System.Timers;
namespace Test { class test { public delegate void TestEventHandler(); public event TestEventHandler TestEvent;
protected Timer TestTimer = new Timer();
public test() { TestTimer.Elapsed += new ElapsedEventHandler(Tick); TestTimer.Interval = 1000; }
private void Tick(object source, ElapsedEventArgs e) {
TestEvent(); }
public void Go() { TestTimer.Enabled = true; } } } The problem that I am facing with, is that the Event runs in a seperate thread and doesn't allow any kind of operation on the Form's controls. The code for the form is given below. CODE using System; using System.Windows.Forms;
namespace Test { public partial class Form1 : Form { test A = new test(); public Form1() { InitializeComponent(); A.TestEvent += new test.TestEventHandler(A_TestEvent); }
void A_TestEvent() { this.Text = "Test Text"; // This is where the Exception "Cross Threaded Operation not valid" is generated }
private void Form1_Load(object sender, EventArgs e) { A.Go(); } } }
How do I invoke the event in the same thread as that of the form's?
Reply
ethergeek
Mar 9 2007, 06:13 PM
It's a new design change either with VS2005 or with the .NET Framework 2.0 to eliminate alot of concurrency bugs. When the exception handler pops up in VS, click the "more info" link...it will take you to an MSDN article explaining how to properly use delegates to do what you want to do in a thread-safe manner.
Reply
iGuest
Apr 6 2008, 09:21 PM
Cross Thread Operations
Help Needed @ C#: Cross-thread Operation Not Valid
Yes , you cannot access a windows forms control or a windows forms component from a different thread. What you need to do in order to access the form controls is to invoke the control using a delegate with the help of control.BeginInvoke(). I have posted an article on the issue with sample code on my blog at http://asadsiddiqi.Wordpress.Com/2007/12/24/responsive-user-interfaces-with-ui-threads/ Hope this helps . Thanks -reply by Muhammad Asad Siddiqi
Reply
magiccode9
Jun 15 2008, 10:11 PM
I have forgotten how the whole sample did. Just remember that you have to use Control.InvokeRequired to check that if you are not on the right thread. If so, skill to the next method call and try to update the control UI. Wish this help Eric
Reply
turbopowerdmaxsteel
Jun 22 2008, 02:28 AM
Here I am posting the full solution to my own problem. Maybe this will help out some beginners. And no, it didn't take me a year and a half to figure this one out, thanks to MSDN. Its just that I didn't bother to look into this once I had the answer. Anyways, here goes it. As said by Muhammad, the trick is in using the Control.BeginInvoke (or Control.Invoke) method to force the method to be executed in the same thread as that of the control. The difference between Invoke and BeginInvoke is that the former is synchronous while the latter is asynchronous. Using BeginInvoke makes more sense as the whole idea is to create efficient multi-threaded application. BeginInvoke starts a new thread passing along a delegate object of the method to be invoked and the parameters to be passed to it. In this case, the BeginInvoke method of the owner Form has to be called from the test class. So, we include an ISynchronizeInvoke parameter in the constructor of the class which is then stored in a member variable. The ISynchronizeInvoke Interface must be implemented in-order to execute a delegate asynchronously. Thankfully, this has been done in the System.Windows.Forms.Control class, so it doesn't require any work on our part. CODE protected ISynchronizeInvoke SyncObject;
public test(ISynchronizeInvoke SyncObject) { this.SyncObject = SyncObject; TestTimer.Elapsed += new ElapsedEventHandler(Tick); TestTimer.Interval = 1000; } We add a new delegate with the same signature as that of the method Tick (the event handler for the System.Timers.Timer's elapsed event). CODE protected delegate void TickDelegate(object source, ElapsedEventArgs e); The Tick method makes sure that it is running in the same thread as that of the Synchronizing object passed to the class's constructor using the Control.InvokeRequired property. If it is not, it calls the BeginInvoke method of the SyncObject passing along a delegate to itself and an object array of it's parameters. No further work is done in this call to the Tick method. After a while, the Tick method is invoked again, only this time on the owner form's thread. The InvokeRequired property returns false and the actual work of the method is done. CODE private void Tick(object source, ElapsedEventArgs e) { if (SyncObject.InvokeRequired) SyncObject.BeginInvoke(new TickDelegate(Tick), new object[] { source, e }); else TestEvent(); } Only one change needs to be made in the Form class - a reference to itself must be passed to the contstructor of the test class. For this, the instantiation of the object is now done inside the constructor (this keyword is only valid inside a non-static property, method, or constructor). CODE test A; public Form1() { InitializeComponent(); A = new test(this); A.TestEvent += new test.TestEventHandler(A_TestEvent); } Full code for the two classes:- Test classCODE using System; using System.Timers; using System.ComponentModel;
namespace Test { class test { public delegate void TestEventHandler(); public event TestEventHandler TestEvent;
protected Timer TestTimer = new Timer(); protected ISynchronizeInvoke SyncObject;
public test(ISynchronizeInvoke SyncObject) { this.SyncObject = SyncObject; TestTimer.Elapsed += new ElapsedEventHandler(Tick); TestTimer.Interval = 1000; }
protected delegate void TickDelegate(object source, ElapsedEventArgs e); private void Tick(object source, ElapsedEventArgs e) { if (SyncObject.InvokeRequired) SyncObject.BeginInvoke(new TickDelegate(Tick), new object[] { source, e }); else TestEvent(); }
public void Go() { TestTimer.Enabled = true; } } } Form ClassCODE using System; using System.Windows.Forms;
namespace Test { public partial class Form1 : Form { test A; public Form1() { InitializeComponent(); A = new test(this); A.TestEvent += new test.TestEventHandler(A_TestEvent); }
void A_TestEvent() { this.Text = "Test Text"; // This is where the Exception "Cross Threaded Operation not valid" used to be generated }
private void Form1_Load(object sender, EventArgs e) { A.Go(); } } }
Reply
Recent Queries:--
"cross-thread operation not valid" - 1.19 hr back. (1)
-
cross-thread c# - 9.35 hr back. (1)
-
c# cross thread calls - 10.41 hr back. (1)
-
cross thread operation c # - 11.53 hr back. (1)
-
c# cross-thread - 15.25 hr back. (1)
-
c# begininvoke thread - 19.92 hr back. (1)
-
cross thread exception - 20.14 hr back. (1)
-
c# cross-thread operation not valid - 1.99 hr back. (2)
-
cross thread opertion not valid - 25.50 hr back. (1)
-
cross-threaded operation not valid - 27.35 hr back. (1)
-
cross-thread operation not valid: - 5.48 hr back. (2)
-
cross-thread operation - 27.92 hr back. (1)
-
cross thread operations event send c# - 32.87 hr back. (1)
-
using invokerequired c# - 32.92 hr back. (1)
Similar Topics
Keywords : needed, c, cross, thread, operation, valid
- Xml Needed?
Is XML required for a text based game? (4)
Help Needed
breaching mac address filter.. (1) /blink.gif" style="vertical-align:middle" emoid=":blink:" border="0" alt="blink.gif" /> hello
guys can any one help me how to bypass mac filter on wifi router. i've got intel 3945abg wirless
mini card.i tried sniffing through wireshark but no use.i know packet injection in not possible with
this card but through airmagnet its possible but still couldn't find those packets. thank u if
any one help me out. /ohmy.gif" style="vertical-align:middle" emoid=":o" border="0" alt="ohmy.gif"
/>....
Space Needed For Database
(10) Iam assuming the information in the databases i will create will be stored in the 500 MB space i
get, but since 500MB isn't enough iam wondering if you guys can tell me how much bytes the
following take: Varchar(x),Tinyint,Text,date,smallint,mediumint,bigint,float.... And the rest
present when you add/edit a row in a table. Also what are the ranges of tinyint,smallint,mediumint
and big int....
Infomation Needed To Add Ram, Gpu, Etc?
(19) I have little ram (Windows says 384mb, CPUZ says 512 in two parts) and I want to add at least a 1gb
stick. I've been told my computer is so old I might need DDR ram, and I should be able to see
somewhere in the computer a label of what I need. My currect GPU is integrated, I want to add
another one to what must be an empty slot, but agian I don't know compatability.
http://img60.imageshack.us/img60/9898/dsc00009jh4.jpg
http://img236.imageshack.us/img236/4388/dsc00010ve6.jpg
http://img75.imageshack.us/img75/9405/dsc00011wy8.jpg http://img76.imageshack.us/....
Free Signature Thread
(3) Hi guys, this is a gift from me to you haha. Fill in the form below and i will get right on it.
Size: Primary colour: Secondary colour: Text: Text colour: Render/sprite/etc: Type of signature:
Eg techncial Any extra information: Recent work: ....
Suggestions Needed For Latest Ycc Bot Maker Breakdown
(5) This is not specifically geared toward Astahost because it is a plea for help for one of the
programs that I am working on. I know there are a lot of smart people here so I decided to give it
a shot. About a week ago I received word that version 1.2 of YCC Bot Maker had stopped working.
This was not a huge surprise as Yahoo! continuously changes its registration process and YCC Bot
Maker is very dependant on the data held in the registration page. I hoped to have a fix put out
fairly quickly but this time I am stuck and have yet to find a solution. From what I c....
Help Needed
(1) I just got my application approved for webhosting package 2 and now I dont have any Idea what to do
next. I recieved an email which says that your application has been approved I went to
www.astahost.com/manage and logged in.but when I tried to login into cpanel it says login attempt
failed. kindly help me out and tell me where Im going wrong . regards....
Cboard!
The official Cboard thread! (0) Hey, myself and Miles are working on a project called Cboard. You've probably guessed what it
is mainly because of the section, but ill tell you anyway! Cboard is a free lightweight simple
but fast bulletin board, coded in PHP with a MySQL backend. Cbaord website:
http://www.cstudios.uni.cc/ Current features: Thread listing (100%) Thread viewing (100%) Forum
listing (100%) Forum viewing (100%) Forum status (0%) Thread posting (100%) Login (100%)
Registration (100%) Profiles (0%) AdminCP (0%) UserCP (0%) News (100%) Stats (100%) Skins (100%) And
more! W....
Javascript Help Needed : Alert(z) Works Fine But Document.write Not
please (2) hi all, I am facing problem in my javascript, any kind of help would be apreciated CODE
function basicFiles(){ //var Z = ""; for (i = 0; i <
document.Form.regionlist.options.length; i++) { var x =
document.Form.regionlist.options[i].value; var y =
document.Form.regionlist.options[i].text; var Z = "regions" +
"[" + x + "]" + " = " + y + ", ";
alert(Z); } } th....
Warning: Mysql_result(): Supplied Argument Is Not A Valid Mysql Result Resource In ...
This Is for My attack Script. (4) Hey. I am making a "Version 2.0" For my attack script, but I can't make it work. This is the
error I am gettin: Warning: mysql_result(): supplied argument is not a valid MySQL result resource
in And here is the code: CODE $dbQueryHealth = mysql_query("SELECT
temphealth FROM characters WHERE user =".
$_POST['atkuser'].""); $currentHealth =
mysql_result($dbQueryHealth, 0); $dbQueryExp =
mysql_query("SELECT exp FROM characters WHERE user = ".$....
Setting Up Cvs On A Sun Unix System
Details needed (4) Can anyone point me to some documentation that details me on setup of a CVS server? I need to setup
a CVS repository on a Sun Unix system with following specs: Machine hardware: sun4v OS
version: 5.10 Processor type: sparc Hardware: SUNW,Sun-Fire-T200 Any
details on which specific version of CVS I should get, the setups (env variables) I need to setup,
any ports I need to setup, would be much appreciated. (Or even links to documentations). I did try
to use Google, but seems like my Google skills have lost its touch. /sad.gif" style="ve....
Skills Needed
(1) Hello, I was wondering if you need to know Javascript to make an online game as I am willing to
learn all I need such as html, css, php etc but was wondering if Javascript is also needed and is it
worth knowing anyway?....
Coders Needed To Help On A Bulletin Board System (BBS)
php, mySql, Graphics design work, etc (4) I recently got involved in a Forum software script which is being developed and thought I should let
everyone know that they need some assistance in the PHP, MySql, Html, and CSS areas. Also, some
Visual Designers would be quite useful. AEF Forum Software is the name of the project. It is
presently in version 1.0.3, and have some pretty cool features already, but in order to advance in
its standings against such Boards as IPB, phpbb, Yabb, etc, more features and Themes are required.
Good bunch of people working hard, but just not enough of us to do everything. Come h....
Basics Of Php For Beginners - Suggestion
Help Needed For Project (5) Hi all, I have a friend who, for his extended IT project is interested in making a website partly
out of php. When he asked for advice my first thought was here. I would like to know some good
websites, tutorials etc that he can use to introduce himself to php (he hasn't done much
before). He is interested in making a simple login/subscription service where you can signup and
then login to a 'members only' page. Any ideas and code samples that you have to share would
be greatly appreciated. /tongue.gif" style="vertical-align:middle" emoid=":P" border="0" a....
Part-passworded, Cross-os External Hd
(5) Soon I will be needing a external hard-drive, mainly for college. I will hopefully have an laptop
with Ubuntu on by then, but I also wanna use school/home(this) computers using Vista/Xp. And
passwords, but not on the whole drive. Any product links or brands I should look out for? Also, is
Ubuntu, Java and Openoffice enough for college? I'll probably get wine, and loads of beer
/tongue.gif" style="vertical-align:middle" emoid=":P" border="0" alt="tongue.gif" />....
Help Needed:: Phpbb2 Mod :: Ip Country Flag 2.9.2
(1) Hi.. I was using IP Country Flag 2.9.2 for my phpBB2 board at: http://www.fun.niranvv.com
Problem 1: I'm facing one issue with the mod. Each and every time, when an user goes to "Edit
Profile" page, The user country will be reseted to the "Non Selected" And the drop down will be
shown like "Select your ISO.... flag" How can I get the default selection in the dropdown as
user previously selected flag? Problem 2: Yesterday I had applied the two fixes for 2.9.4 as
mentioned here: http://www.phpbb.com/community/viewtopic.p...903810#p2903810 and here: h....
Photographers And Artists Needed
(2) No…No.. its not some scam and yes its true I don’t have any money to pay you. But I
thing you can benefit from this: I have this new site that makes email signatures that look like
business cards. Visitors can choose a background then write their stuff on it. I need lots more
backgrounds for my visitors to use as a base for their card. The background images are pretty small
301px by 177px and really lend themselves to close-ups or abstract. What I’m offering:
Where ever your image is displayed on my site you will always have a good anchor text li....
Juggling An Iframe Box With Xhtml Sites
How to make it strict and valid (8) You most likely have encountered a situation (as a web developer) where you have an iframe box and
you are using valid XHTML Strict. Iframes are still valid in FRAMESET and TRANSITIONAL XHTML but it
is best to use XHTML 1.0 Strict or XHTML 1.1 (application/xhtml-xml). A method for including iframes
have been found. It doesn't use the tag at all. Since tags are depreciated, new tags/CSS are
to replace them (except DOM, which is a little off topic here). The and tags were replaced by
. Yes, is for inserting any foreign object into XHTML documents. Since I....
Help Needed Finding A Company For Some Office Work
(4) I'm having some serious computer issue, not sure its a virus or what, but I had geek squad come
to my house in the past and they are very expensive. I'm in minneapolis, anyone recommend a good
computer service company. I found http://www.rescuetechusa.com but i never heard of them
before. Thanks Bill....
Help Needed To Create Windows Startup Script!
(4) Hi all, I need a help from any one out here! I need to display one confirmation box using
windows startup script! I need to run this script on each and every client system in my
LAN! Here is the requirement: The script should ask the user to click yes to continue or no to
exit. If the user click yes, that should open Internet Explorer with some site , Say google.com and
after filling some forms and after closing the browser, that should bring to regular login screen
which says, cntrl alt del to login! If the user directly preses the no button, that sho....
Links: Free Stuffs Needed For Webmasters!
Free Domain And Redirection Services, Free Stuffs Needed for website O (15) Hi all, Im posting some FREE stuffs needed for all the web masters out here! You can view the
Index here: www.fun.niranvv.com/viewtopic.php?t=281 Free Templates
http://www.steves-templates.com/ http://www.freewebtemplates.com/ http://www.templatesbox.com/
http://www.freelayouts.com/ http://www.freshtemplates.com/ http://www.zerodollartemplates.com/
http://www.effex-media.com/ http://www.templatesbox.com/
http://www.mastertemplates.com/free-templates.htm http://www.templateyes.com/
http://www.templateworkz.com/ http://www.4layouts.com/ h....
Help Needed To Mke Phpbb Sub-forum
(4) can anyone tell me how do i add a feature to add sub-forums to phpbb forums? i also want cash mod
to work on it.. i tried categories hierarchy but it clashed with cash mod... doesnt work... can u
ppl suggest something for this?....
Sprites Needed.
for RPG Maker XP (2) My friends and I are making a game using the RPG Maker XP for PC. The thing is, we need a pixel
artist or someone that can make sprites for our game. We need ninja sprites, samurai sprites,
Japanese people sprites, and a large panda sprite. Any of your help would be accepted.
-------------------------------------------------------------------- Please don't tell me to do
it myself or about how bad rpgmaker is.....
Help Needed In Setting Up AdSense In IPB
(7) Hey guys /smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" /> , I
just installed Invision Power Board on my AstaHost account. Everything is alright with the board. I
just need to know how to add in those banner ads like this one AstaHost uses After all this over
I also need help in adding my Google Adsense ad on my forum (on the top left, for example right to
AstaHost logo). If anyone here has signed up for the Google Adsense service, can give me the code
for making by banner ads transperent because I dont seem to get the right color c....
Advice On MP3 Player Needed
Must have FM tuner + min. 2 GB capacity (22) Hello all ! Someone I know is flying to Dubai and has very kindly agreed to get me any
electronic consumer goods that I want. Right now, a personal music player is at the top of my "I
want this..." list. However, I want to ask the advice of users on the forum as to what particular
model they'd suggest. The following parameters are must-haves: At least 2 GB capacity FM
tuner ability to play WMA, MP3 - a must. (Plus points if it can also play MP4 / OGG / AAC) good
battery life - 10 - 12 hours actual playback (which means a rated life of about 14 hours) I d....
Is A Sound Card Absolutely Needed ?
(18) Hi, I've been without a sound card for quiet awhile (I think forever /tongue.gif' border='0'
style='vertical-align:middle' alt='tongue.gif' /> ) but just curious if they're really needed
for gaming, I only use a headset. Though sometimes my Counter-Strike Source game will freeze up
would a game freeze up due to 'too much sound' and because I have no sound card it can't
render all the noise at once. Okay maybe I'm blabbering on a bit, to be honest I have no clue
about the hardware aspect of computers. But do you need a sound card now days?....
Help Needed: Monitor Out Of Timing
Out of Timing error with certain apps (6) I've decided to convert to an LCD monitor over the CRT, which I believe to be infinitely better.
Anyway there are certain applications that, when I start up, the monitor goes black and a message
says: Out of Timing H: 43 Hz V 27kHz. Or something like that. Any help? Drivers are up to date, and
I think it's not influenced by resolution. I'd like to get this to work because it was
rather large investment. Thanks.....
Help Needed To Create Login Script With Perl/cgi
Need Script (21) Have a format in mind and have a good idea how it works. So here what I need: step 1::: person must
register: create handle // enter password // enter password // enter email : it then takes the
person to acsepted page or reject per reason page. step 2::: login page: enter handle // enter
password : takes them on it to the site of their control pages for each handle controls their own
pages yet all pages interacts with the others. or bad password re login page. Have the page
designed already have the script in html lang but one can create a password on the html page but....
Mobile Phone Ringtone Converter
Software needed (7) The other day i was wondering if i could convert my mp3 collection into ringtone files for my
mobile. It's a Motorola C350. It supports polyphonic tones. I have a cable for it. I downloaded
a few ringtones over GPRS and they are in .mid format but i cannot play them using windows media
player. Can anyone suggest a software that i can use to convert mp3's into the format used by
mobiles.....
Help With Some Php Or Maybe Asp
help needed (5) Hi Too all first of all I want to say I need 10 posts badly so lets help each other lol! Ok and
now the real part I need some help with php because Im pretty new to it (really im not a big fan of
php I like asp more but as asp is an Microsoft protuct its not cheap so have to start liking PHP
/laugh.gif' border='0' style='vertical-align:middle' alt='laugh.gif' /> ) I need too include a
part of one site in my site that meens i dont need the whole site onlia a smal part. I found the way
but it loads very slow so im trying to find an other way. Heres the code maybe ....
Looking for needed, c, cross, thread, operation, valid
|
|
Searching Video's for needed, c, cross, thread, operation, valid
|
advertisement
|
|