Murugan.com
Murugan Andezuthu Dharmaratnam

  |  HOME   |  BLOG   |  TWITTER   |  ARTICLES   |  8086  |  C++   |  VC++   |  ASP .NET   |  VB .NET   |  JAVA SCRIPT   |  MS SQL   |  PHP   |  MY   |  VIDEOS   |  DOWNLOADS   |  CONTACT ME   |  



ASP NET Cross thread operation not valid Control accessed from a thread other than the thread it was created on


Home  > ASP.NET  > ASP NET Cross thread operation not valid Control accessed from a thread other than the thread it was created on 
       
Cross-thread operation not valid: Control 'lblCounter1' accessed from a thread other than the thread it was created on.


This is a common problem. I will provide solution with an example




This is a simple WinForm with two labels

Below is the working code to update the lables using a thread. 

Here the main point u have to see is that. controls in the main forms cant be updated from another thread. to do it we use an invoke 
Control.Invoke  Method (Delegate) (System.Windows.Forms)
Executes the specified delegate on the thread that owns the control's underlying window handle.


Here are more details on invoke 
Delegates are similar to function pointers in C or C++ languages. Delegates encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code that calls the referenced method, and the method to be invoked can be unknown at compile time. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and more secure.

The Invoke method searches up the control's parent chain until it finds a control or form that has a window handle if the current control's underlying window handle does not exist yet. If no appropriate handle can be found, the Invoke method will throw an exception. Exceptions that are raised during the call will be propagated back to the caller.


    Public oThread As System.Threading.Thread
    Public strThread As String = ""
    Public strSelector As String = ""
    Public Sub ThreadWrite()
        Select Case strSelector
            Case "Counter1"
                lblCounter1.Text = strThread
            Case "Counter2"
                lblCounter2.Text = strThread
        End Select
    End Sub


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        oThread = New System.Threading.Thread(AddressOf ThreadCode)
    End Sub
    Public i As Integer = 0
    Public j As Integer = 0
    Public bFlag As Integer = 0
    Private Sub ThreadCode()
        Do While True
            strSelector = "Counter1"
            strThread = i.ToString
            lblCounter1.Invoke(New MethodInvoker(AddressOf ThreadWrite))
            strSelector = "Counter2"
            strThread = j.ToString
            lblCounter1.Invoke(New MethodInvoker(AddressOf ThreadWrite))
            bFlag = bFlag + 1
            If bFlag = 2 Then
                bFlag = 0
                j = j + 1
            End If
            i = i + 1
            System.Threading.Thread.Sleep(500)
        Loop
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        oThread.Start()
    End Sub



activex mdb

com smartcard

GetLastError() in VC++ Win32 Display the Value in a MessageBox

VC++ DWORD To String

VC++ Win32 compare string with empty character constant

VC++ Win32 Compress Video To Mpeg

MVC

System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client

<%#(Container.DataItem("Datetime"))%> how to formar output to display only date

ajax PageMethods System InvalidOperationException

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.

ASP .NET Ajax PageMethods Returned an System.InvalidOperationException While Trying to return a dataset.

Asp .net check if a string is numeric

ASP .NET Create a file

asp .net create directory

ASP .NET Disable Back Browser Button

asp .net disable cache or cahing

ASP .NET domain name to ip resolution, Get IP Address Given Host Name

ASP .NET Drop Down List Default Value

ASP .NET drop down list hide list items

ASP .NET Error Exception Conversion from string "07-18-2009" to type 'Date' is not valid

ASP .NET Exception The element 'buildProviders' cannot be defined below the application level. in ajax project

asp .net find all files in the directory

asp .net find first findnext

ASP .NET How to Populate a TreeView Control With TreeNode s Using recursive algorithm or recursion

asp .net repeater control pass commandargument OnItemCommand

ASP .NET Send Mail from YMail or Yahoo Mail using MailMessage SmtpMail

ASP .NET VB .NET Code connect to sql server using sql authentication sql connection string

ASP .NET Yahoo Mail Y Mail The SMTP server requires a secure connection or the client was not authenticated. The server response was: authentication required

ASP NET Cross thread operation not valid Control accessed from a thread other than the thread it was created on

ASP NET Get Threads Current State

ASP NET How to get a sessionid

ASP NET Howto Store Session In Database WebFram

ASP Net IX WebHosting Session Not Stored Problem

ASP.NET & VB how to clear the text of a textbox on a mouse click after the page loaded

Asp.net &vb How to upload image file into a folder in the server and to view the thumbnail of the image after uploading complete

ASP.NET ,The breakpoint will not currently be hit. No Symbols have been loaded for this document.

asp.net auto complete dropdown list

Asp.net How to put the some values from database to calendar column

Asp.net How to refresh a tree view after each activity like add new node,update node and delete node

ASP.NET How to Upload files and image and view the uploaded file contents

ASP.NET How to upload the file and images and view the contents of the uploaded files

asp.net Tree view -Error parsing control:Object referance not set to an instance of an object

ASP.NET,Datagrid Checkbox .checked value is always False even i select the checkbox

ASP.NET,How can i dynamically add new columns to a datagrid

ASP.NET,how to change the color in datagrid based on this condition from db?

ASP.NET,How to resize an image before displaying it to the image field

ASP.NET,Logout Problem,How to disable browser back button after logout .

Conversion from type 'DBNull' to type 'String' is not valid.,asp.net&vb

convert html code to display in web pages

Convert integer to unicode

CS0104 Menu is an ambiguous reference between System.Web.UI.WebControls.Menu and xxx.includes.Menu

Data View Row Filter

Declare a Multidimensional Byte Array

drop down from text bar like google

Enable javascipt in ajax

ExecuteReader: CommandText property has not been initialized, asp.net,vb,mtablestring in getsqldata function

Gmail ASP .NET System.Net.Mail Send Mail Using Gmail MailMessage SmtpClient

godaddy System.Web.HttpException: Validation of viewstate MAC failed. hosted by a Web Farm or cluster machineKey configuration validationKey validation algorithm

google drop down auto complete

how can i display rows in a dataset as columns of a DataList

How to read/view the uploaded files other than .txt like .doc,.pdf

HtmlAgilityPack Input string Error

HttpRequestValidationException

HttpUtility.HtmlEncode Preserve Enter or CrLf ASP .NET

IIS 7 The requested page cannot be accessed because the related configuration data for the page is invalid.

index

Invalid postback or callback argument.

Invalid postback or callback argument. Event validation is enabled using

Nested DataGrid DataList Repeater

NullReferenceException was unhandled by usercode,Objectreference not set to an instance of an object

PageMethods not getting called javascript

PageMethods Return dataset

PageMethods System.InvalidOperationException

PageMethods System.InvalidOperationException ASP .NET Ajax Problem Occurs while returning DataTable on call of System.Web.Services.WebMethod

Parser Error: Unknown server tag 'asp:ScriptManager'

RegisterStartupScript how does it work

registerstartupscript when does it get called

Send Mail The SMTP server requires a secure connection or the client was not authenticated Exception ASP .NET

Server was unable to process request. is not a valid virtual path.

SmtpFailedRecipientException was unhandled by user code

Specified argument was out of the range of valid values.

StackOverflowException was unhandled

System Web HttpException Request timed out

System.Web.Hosting.HostingEnvironmentException: Failed to access IIS metabase.

System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (ctl00$ContentPlaceHolder1$txtContents="


The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value

the imported project file could not be loaded. root element is missing Visual Studio 2005

Unable to cast object of type 'Microsoft.VisualBasic.Collection' to type 'System.Data.DataSet'.

Unable to cast object of type 'System.Data.DataSet' to type 'System.Data.DataView'.

UpdatePanel Not get called ajax codebehind beakpoint never gets hit

VB NET Get Windows System Directory

VB NET Remove all non alphanumeric characters

VB NET WebBrowser Control Editable

Visual Studio Net 2005 Open in Firefox

web services persient data

XML Parsing Error not well formed

Yahoo Mail ASP .NET System.Net.Mail.SmtpException: Failure sending mail. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host

Yahoo Mail YMail Server does not support secure connections. ASP .NET smtp.mail.yahoo.com MailMessage oSmtpClient System.Net.Mail

ASP .NET C .NET Find String between two string or substring



  |  HOME   |  BLOG   |  TWITTER   |  ARTICLES   |  8086  |  C++   |  VC++   |  ASP .NET   |  VB .NET   |  JAVA SCRIPT   |  MS SQL   |  PHP   |  MY   |  VIDEOS   |  DOWNLOADS   |  CONTACT ME   |  

Copyright 2009 @ Murugan Andezuthu Dharmaratnam