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

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

InvalidOperationException within Lock

Posted By:      Posted Date: October 25, 2010    Points: 0   Category :.NET Framework

I have a collection in a singleton class, called _connectedNodes of type SynchronizedCollection<RemoteMachine.Node>. EVERY single call to access this collection is wrapped in a lock statement identical to the one in the snippet below.

lock (_instance._connectedNodes.SyncRoot)
	foreach (RemoteMachine.Node node in _instance._connectedNodes)
		if (node.Connection.State == RemoteMachine.ConnectionState.Normal)
This code is basically using async sockets to send messages to a group of connected nodes. How could I have had a 'collection was modified' error within this snippet?

View Complete Post

More Related Resource Links

Concurrent Affairs: Build a Richer Thread Synchronization Lock


In my last column, I showed the various thread synchronization mechanisms employed by the Microsoft® . NET Framework (see Concurrent Affairs: Performance-Conscious Thread Synchronization). I then examined the performance characteristics of all these mechanisms and determined that the Interlocked methods performed the best because the calling thread never has to transition to kernel mode.

Jeffrey Richter

MSDN Magazine March 2006

Memory Models: Understand the Impact of Low-Lock Techniques in Multithreaded Apps


Because the use of low-lock techniques in your application significantly increases the likelihood of introducing hard-to-find bugs, it is best to use them only when absolutely necessary. Here Vance Morrison demonstrates the limitations and subtleties low-lock techniques so that if you are forced to use them you have a better chance of using them correctly.

Vance Morrison

MSDN Magazine October 2005

C++ Q&A: Performance Monitoring, Managed Extensions, and Lock Toolbars


In the June 2004 issue of MSDN®Magazine, I described a class called ShowTime that you can use to do simple performance monitoring for your app. ShowTime uses its constructor/destructor to record the start/stop times of its existence so you can instantiate it in a block of code like so: { ShowTime st(_T("Total time is:")); // some lengthy operation } .

Paul DiLascia

MSDN Magazine September 2004

System.InvalidOperationException: Invalid attempt to read when no data is present.


Invalid attempt to read when no data is present.

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.InvalidOperationException: Invalid attempt to read when no data is present.

Source Error: 

Line 53:             if (reader.HasRows)
Line 54:             {
Line 55:                 Response.Write(reader.GetString(0));

Here is my code:

VS 2010 Designer InvalidOperationException after using Blend 4 VSM

Working on an WPF 4 app today and noticed the VS 2010 Designer won't load after using Blend 4 Visual State Manager. Basic info that I did. 1. Had a Button.  Would display in both VS10 Designer and Blend 4. 2. In Blend 4, I right clicked Button -> Edit Template -> Create Empty. 3. Added ContentPresenter to Grid. 4. Back in Window.xaml, added Image to Button's ContentPresenter.  Still works in both VS10 and Blend 4. 5. In Blend 4, went back to Edit Template and modified some of the States.     - Disabled: Grid Opacity 50%     - MouseOver: Grid Scale X/Y to 1.1     - Pressed: Grid Angle 15. 6. Save and go back to VS10, the designer won't load.  Get the Yellow bar at top stating something like... InvalidOperationException was thrown on "button": Property does not point to a DependencyObject in path...... The button now has an X with red circle in it. Is this a know issue?  Is there a fix? It still works in Blend 4 and I can run the WPF app in both VS10 and Blend 4. Thanks in advance.

Lock the window size to uniform in wpf

I have a window that contain a ViewBox. The ViewBox's Streach property is set to Uniform. And I want to set the window size to be uniform! that means the Height And Width properties are relative to each other.

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        

ThreadPool with lock isn't thread safe

Hello, I'm having some problems with my code which apparently isn't thread safe at all. The problem is that it doesn't crash often, but of course it does when in production! I have twisted my mind around the problem for a month or so now, and I need some help in sorting out the problem. Well, the problem is that it isn't thread safe, and the collection (_subscribers) is modified while looping. The error says that it crashes in the method: SendRoundSettings. Here's part of the code (which I guess contains the error, as the other methods are pretty much identical): [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)] public class DuplexService : IDuplexService { private readonly object _syncRoot = new object(); private static Subscribers _subscribers = new Subscribers(); private static RoundSettings _currentRoundSettings = new RoundSettings() {CompetitionId = 1, NumberOfAthletesInRound = 0, Round = 0, SortDirection = SortDirection.ByStartNumber}; public void SendJudgeScore(CompetitionJudgeAthleteJump judgeScore) { ThreadPool.QueueUserWorkItem(state => { Subscribers clonedSubscribers = CloneSubscribers(); Console.WriteLine("Sending judgeScore to {0} client(s)", clonedSubscribers.Count(x => x.CompetitionId == judgeScore.CompetitionId));

How to lock tables during a transaction

Hi, is there a way do something like this:  BEGIN TRANSACTION --lock table1 --do work here --unlock table1 COMMIT TRANSACTION

Why does RowLock result in a Page Lock

Hi, I am having a problem where even though I have indicated a rowlock it results in a page lock and a subsequent process is unable to access the table till the first process has commited.   Sample code is below.   Process 1 Begin Transaction SELECT EmpName FROM fEmployee WITH (ROWLOCK) WHERE EmpNo = 1 PRINT fEmployee.EmpName -- will print 'Sam' UPDATE fEmployee SET EmpName = 'Bob'  WHERE EmpNo = 1 .... .... .... Lots of other related processing takes place here and then finally COMMIT TRANSACTION Process 2 Begin Transaction SELECT EmpName FROM fEmployee WITH (ROWLOCK) WHERE EmpNo = 2 PRINT fEmployee.EmpName -- will print 'Rick' UPDATE fEmployee SET EmpName = 'Paul'  WHERE EmpNo = 2 .... .... .... Lots of other related processing takes place here and then finally COMMIT TRANSACTION When I run process 1 and process 2 at the same time, till process 1 commits the transaction, process 2 does not perform the Select and print the name. Why is this the case as they are both selecting different records and the Select has specifically indicated a RowLock. What I noticed was that when the rows are in the same page this problem occurs, while if the records are in different pages (assuming the data is large in the table and the gap between the empno's are large) it does not occur. Any help appreciated. Thanks

Cannot lock request 254,023

Hi, I have been running SSIS job for loading 26 million records from SAP source to SQL Server table having 20 columns. there are no transformations in my DFT. after DFT i have Execute SQL Task to get the target count. 26 million records have been successfully inserted into the table but job failed with below error:"Source: DFT_BW_TO_STAGING SAP BI Source     Description: Cannot lock request 254,023  End Error  DTExec: The package execution returned DTSER_FAILURE (1)." What could be the reason behind this result. Any help would be greatly appreciated.Das

Lock statistics

Hope this is the correct forum. I know you can collect real-time information about locks. But are there any historical data that can be fetched per database?

Lock statistics

Hope this is the correct forum. I know you can collect real-time information about locks. But are there any historical data that can be fetched per database?

InvalidOperationException error with jquery call to webmethod

Hi, I'm having an issue which results in returning the following from XHR requests to an webmethod on my form. {"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}Simplified form Code is as follows. [WebMethod]        public string LoadContact()        {            return string.Format("Hello From Server");        }I'm using JQuery to make the call: $.ajax({            type: "POST",            url: "SYS_AjaxResearch.aspx/LoadContact",            data: "{}",            contentType: "application/json; charset=utf-8",            dataType: "json",            success: function(msg) {                $("#topPanel").text(msg.d.LoadContact);   

Sharepoint sub site lock

How to lock Sharepoint 2007 sub site.I used stsatm-o setsitelock it locks site collection. I want to lock only particular site only. Ex: If i want to lock http://sharepoint/site1 only lock on site1 not for Http://sharepoint Please suggest me object model code for this. Thakns Anil  

System.InvalidOperationException: Timeout expired.

Hi I am getting the following error on my page:System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached. at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.SqlClient.SqlConnection.Open() at _default.commentCount(Int32 ArtID) at ASP.default_aspx.__DataBind__control4(Object sender, EventArgs e)....I thought I had closed all the connections in my code:Imports System.Data Imports System.Data.SQLClient Partial Class _default Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load commentDisplay() End Sub Sub commentDisplay() Dim pageno As Integer = Request.QueryString("page") Dim MyConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("nbb").ConnectionString) Dim MyDataAdapter As SqlDataAdapter MyDataAdapter = New SqlDataAdapter("art_getHomepage", MyConnection) MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
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