.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Post New Web Links

How to Solve Cross-thread operation not valid: Control " accessed from a thread other than the threa

Posted By:      Posted Date: August 28, 2010    Points: 0   Category :.NET Framework
I have a thread... like Dim a As new Threading.Thread(Address Of generate) Dim WithEvents lst As New ListBox()   Form_Load() Me.Controls.Add(lst) lst.SetBounds(100,100,150,80) End Sub   Button1_Click() a.Start() End Sub   Sub generate() Dim i As Integer For i = 1 To 10 lst.Items.Add(i) Next End Sub   When i run this program it results in the above mentioned Exception - Cross-thread operation not valid: Control " accessed from a thread other than the thread it was created on." What is this actually? Why it has been thrown..? Kinda help me please..... Thanx in advance

View Complete Post

More Related Resource Links

Cross-thread operation not valid


I have .net 1.1 compact framework project, which is now migrated to 3.5 compact framework. The project has lot of cross thread calls. The Project runs perfect in .net 1.1, but fails in 3.5.

I keep getting an error "Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on." while executing the following code. _currentForm.Controls.Add((Control)_controlList[0]);

some suggested to set Control.CheckForIllegalCrossThreadCalls=false for the form, but unfortunately compact framework don't support CheckForIllegalCrossThreadCalls property.

Request somebody to help me, by educating on how to handle this situation in .net 3.5 compact framework.

System.InvalidOperationException: Instance operation is not valid on workflow runtime thread

Am getting the exception related in the title of this article when using the StateMachineWorkflowInstance object to arbitarily set state in my workflow code; and am unsure why.  The code follows below:   500     Protected Overrides Function Execute(ByVal executionContext As System.Workflow.ComponentModel.ActivityExecutionContext) As System.Workflow.ComponentModel.ActivityExecutionStatus   501    502    506         Dim smwi As StateMachineWorkflowInstance = New StateMachineWorkflowInstance(StaticWFRuntime.LocalRuntime, Me.WorkflowInstanceId)   511    512         'set workflow-wide database connection string   513         _connectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString   518    519         Utility.LogEnabled()   520    521         Utility.FoaeaLogger.WriteEntry("Processing TracingApplication.Execute()....", EventLogEntryType.Information)   522         If StaticWFRuntime.LocalRuntime Is Nothing OrElse StaticWFRuntime.LocalRuntime.IsStarted = False Then   523             Utility.FoaeaLogger.WriteEntry("No static RuntimeService object exists!", EventLogEntryType.Warning)   524         End If   525    526         Return MyBase.Execute(executionContext)   527    528     End Function   796     Private Sub gotoState2_ExecuteCode(ByVal sender As System.Object, ByVal e As System.EventArgs)   797    798        

Cross-Thread Exception at a WinForms control hosted by the WindowsFormsHost in WPF



I have a WPF Application and inside hosted existing WinForms controls.

In WPF i'm using the 'Dispatcher' with the 'CheckAccess' method to check if invoke is required, in my old WinForms controls i use 'InvokeRequired'.

The problem is, that if one of the WinForms controls gets created but not yet shown (drawn) and the application gets to the line, where it has to invoke, the InvokeRequired property returns 'false' even the code is not running under the Main Thread and so it resumes in a Cross-Thread exception.

The strange thing is, that it works fine, when the control gets visible (drawn) before changing it (in my case by switching to the specific tabpage).


For me it seems as if the 'InvokeRequired' property doesn't work reliable when the WinForms control gets hostet by WPF.


It would be great, if someone has experience with this issue and could help me!





SharePoint 2010 Publishing Site : Operation is not valid due to the current state of the object.

  I think as usual, the new version of SharePoint 2010 has a lot of problems. the below messege appear in a publushing site (FBA) enabled and when I try to access the pages list or even approve a page of accessing the SiteCollectionImages list and ......... etc every link produce the below error. I'm very frustrated with 2010.  Server Error in '/' Application. <nativehr>0x8107058a</nativehr><nativestack></nativestack>Operation is not valid due to the current state of the object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Runtime.InteropServices.COMException: <nativehr>0x8107058a</nativehr><nativestack></nativestack>Operation is not valid due to the current state of the object. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [COMException (0x8107058a): <nativehr>0x8107058a</nativehr><nativestack></nativestack>Operation is not valid due to the current state of the object.] Microsoft.SharePoint.Library.SPR

Operation is not valid due to the current state of the object

Dear people. Help me, please. I create simple sample project  Business Data Connectivity Model on Visual Studio 2010 (standard sample "Hello World") I edit file "Feature1.Template.xml": <?xml version="1.0" encoding="utf-8" standalone="yes"?> <Feature  Id="bf21f627-600c-4eec-8c01-a49dac59a05a"           Scope="Farm"           xmlns="http://schemas.microsoft.com/sharepoint/"> <Properties> <Property Key="GloballyAvailable" Value="true" /> <Property Key="SiteUrl" Value="http://win-mne65kpc063/ForTestBCS"/> </Properties> </Feature>   I have Sharepoint Server. Site's local URL : http://win-mne65kpc063/ForTestBCS I press F5, and see error:       Error 1 Error occurred in deployment step 'Add Solution': Operation is not valid due to the current state of the object.   0 0 BdcModelProject2 If I make deployment by the Central Administration, I have no error. But, when I display external list whith BCS-model I get error: Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown. <detail><errorstring xmlns="http://sch

InvalidCastException when calling JavaScript from C# control using a second thread.

Original Issue: I need to be able to call functions in the JavaScript of an HTML page (not ASP.NET) from a C# object embedded in that page.  The c# object has to be .NET 2 level. So I created a C# DLL assembly in VS 2010 which contains a class called NoUIControlClass. set the target framework to .NET 2.0 and made sure to check "Make assembly COM-Visible".  I also signed the assembly so it would have a strong name so I could install it in the GAC.  So far so good. Here is the batch file I run after the project is built to register the control and place it into the GAC: copy "C:\Users\x\Documents\Visual Studio 2010\Projects\NoUIControl\NoUIControl\bin\Debug\NoUIControl.dll" C:\Exploration\NoUIControl C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm NoUIControl.dll /unregister C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm NoUIControl.dll NoUIControl.dll C:\"Program Files (x86)"\"Microsoft SDKs"\Windows\v7.0A\Bin\gacutil.exe /u NoUIControl.dll C:\"Program Files (x86)"\"Microsoft SDKs"\Windows\v7.0A\Bin\gacutil.exe /i NoUIControl.dll This works and all is good.  Next I've turned the security level in IE all the way down for intranet and trusted sites.  Just to make sure that doesn't get in the way.  Here is the HTML file I serve from the web server. <html> <head

{"Operation is not valid due to the current state of the object."} using WebService

Hi, i am using this method to insert managed paths into my WebApplication using the object model in a Web Project, but it seems that it's not working, always give me the bellow error: 1 - Content Database have AppPool user as DbOwner 2 - I can create site collections, but is writing in the SPWeb direcly, so when i use the WebApplication it will give me always the same error ERROR    at Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context)    at Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(HttpContext context)    at Microsoft.SharePoint.Utilities.SPUtility.ValidateFormDigest()    at Microsoft.SharePoint.Administration.SPPersistedObject.Update()    at Microsoft.SharePoint.Administration.SPWebApplication.Update()    at Microsoft.SharePoint.Administration.SPAutoSerializingObject.UpdateParent()    at Microsoft.SharePoint.Administration.SPPrefixCollection.UpdateParent()    at Microsoft.SharePoint.Administration.SPPrefixCollection.Add(String strPrefix, SPPrefixType type)    at WsCreateAddPaths.<>c__DisplayClass3.<CreateAddPaths>b__1() in c:\VS2010\SGE\App_Code\WsCreateAddPaths.cs:line 36    at Microsoft.SharePoint.SPSecurity.CodeToRunElevatedWrapper(Object state)    at Microsoft.SharePoint.SPSecurity.<>c__DisplayCla

Backup failing - Error "operation is not valid due to the current state of the object" ...........Ca

Hi, I am having a problem backing up a site collection, when trying to backup the collection I get the following error  "operation is not valid due to the current state of the object"............. "Category Info :InvalidData" . I'm getting the same error whether I use CA "granular backup" or "Farm backup", and using either STSAMD or Powershell. I can backup CA or the mysite collection but not the Home Portal site collection. As this is a production system I am really worried that something is going to happen and I'll have no backup. Does anyone have any suggestions on what i can do to either fix the problem or an alternative way to backup the collection or farm.  P.S. I am not using the "UseSQLSnapshot" parameter. Any ideas ? 

Bind control to results from thread

Hello,  I can't find best practice to my issue, I will appreciate any help from you – Please let me know what you think about it:  My application request data by threads. Each thread have those events: OnStarting – Fires just before the thread start its job. OnFound – Can be fire more than one for each thread. The result from thread can be received here OnFinish - Fires just after the job finish.  The scenario is something like that: Let's say I have WinForm contains RadioButton for "Search Type" and Button for "Start Search". The user choose the search type and press on "Start Search". According the search type the form knows to place new control like Grid or TextBox on the form. The result from thread (The thread do the searching job) should display in the appropriate control which opened for this specific search.  My question: What is the best practice to bind control to the result from thread ?   Options: 1.     Save Key=Value list for Thread=Control 2.     Create MyGrid / MyTextBox with even OnFill. The application will use OnFill as callback in the threads. 3.     Any other suggestion will be very welcome.   Thanks in advance !

Get Control that triggered cross page postback

Hi I want to know if there is a way to get the control that triggered the postback,such as I have one page Page1.aspx with two buttons like<asp:Button id="btnCrossPost" runat="server" Text="Post To Another Page" PostBackUrl="Page2.aspx" CommandArgument="1"/><asp:Button id="btnCrossPost2" runat="server" Text="Post To Another Page 2" PostBackUrl="Page2.aspx" CommandArgument="2"/>and in Page2.aspx I want to get which button triggered the post back so that I can get the command argument which is vitalto the processing of the next page.Thanks.

cross thread problem



Im using vs 2010 to try and make an application. It uses multi threading and im trying to change a label on my main form from within the threads but im getting this error : Cross-thread operation not valid: Control 'log' accessed from a thread other than the thread it was created on.

Ive read lots of articles on the web about delegates etc but its too confusing for me :(

Can anyone explain it to me please in newbie language ?

Thanks in advance.


Is Dispatcher.BeginInvoke really NOT thread safe, while the old System.Windows.Forms.Control.BeginIn




System.Windows.Forms.Control.BeginInvoke is documented as thread safe (in fact, BeginInvoke , EndInvoke , Invoke , InvokeRequired , and CreateGraphics are).



But in WPF, Dispatcher.BeginInvoke is not documented as thread safe. Which would appear to me as a regression (and not really convenient, to be honest).

Was it only forgotten in MSDN documentation, or should I really use external locking to prevent the dispatcher to get lost in its messages and priorities?



Thanks. ;)

when adding web reference, I get "Operation is not valid due to the current state of the object."



I am trying to add a Web reference to a project.  So, I do the standard: right clicking on the project and select "Add Web Reference". The Add Web Reference appears and I navigate to the desired URL "http://ws.melissadata.com/dqws/Address.asmx" and click "Go".   This works in IE.  I see the results and two methods in the window.  However,  the "Add Reference" button and " Web Reference Name" texbox is disabled. And, I see the Operation is not valid due to the current state of the object." I think this is a proxy and or firewall issue?


I know the System.Net.WebProxy("corp-xxx-proxy.xxx", 8080);  and System.Net.NetworkCredential("xxxx", "xxxx"); [x replaces real values]

 Any ideas where I can set this info so I will be able to use the "Add Web Reference" wizard?  - OR - Is there a workaround?




HTTP Module :Item.Update() gives exception 'Operation is not valid due to the current state of the


Hi, I have created a http module to update the list item but when i use the Update function of SPListItem object it gives the error: "Operation is not valid due to the current state of the object". Below is the HTTP Module i have written to update the List Item. Please suggest






public class SiteUsage : IHttpModule



Operation is not valid due to the current state of the object at Microsoft.SharePoint.WebControls.S

I have this  problem. When I run this piece of code all I get is

1. I get this error at SPWebApplication webApp = webAppBld.Create();

2. {"Operation is not valid due to the current state of the object."}

3. Stack gets here "   at Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context)

                SPFarm objSpfarm = SPWebService.AdministrationService.Farm;
                SPWebApplicationBuilder webAppBld = null;

                webAppBld = new SPWebApplicationBuilder(objSpfarm);
                webAppBld.Port = 33665;
                webAppBld.Id = System.Guid.NewGuid();

                webAppBld.AllowAnonymousAccess = false;
                webAppBld.UseNTLMExclusively = true;
                webAppBld.UseSecureSocketsLayer = false;

                webAppBld.ApplicationPoolId = "SharePointAppPoolId-33665";
                webAppBld.ApplicationPoolUsername = @"testsvr02\testadmin";

                // build the password as a secure string
                SecureString appPoolPwd = new SecureString();

pls advice me which control is suitable for this operation


I am developing application for Hotel Management system.

I want to show the Availablity and Rates as shown as below. 
First Row   : Room Type Name Ex: Deluxe Room
Secount Row : Day1 Day2 . . . . Day31   Ex: 01-Oct-2010  02-Oct-2010  03-Oct-2010.... 31-Oct-2010
Third Row   : Vailablity                Ex: 15           15           15              15

control not working when created on new thread



I recently read this article and implemented -


I changed my control (dev express pivot grid) to be created on a secondary background.

The control is loading and displaying faster (great) but now if I try t omove the scrollbar etc nothing happens. The control has stopped responding to events.

Can anyone tell me how to resolve this issue. I'm not exactly sure where to start looking.

I need a way of getting the mouse drag events across to my control on the secondary thread.


ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend