I want to know why it's happening me this error: Object synchronization method was called from an unsynchronized block of code.

I'm developing a Smart Array (it's a request I cannot use a List of int that I know it's easier because I made both codes). I have done this class and below is the example of how I use it. The error is often in this line (153 from class):
// Ensure that the lock is released.
Monitor.Exit(array);
If I use a List nothing wrong happens just when I translate to an array. Thanks for your help.
SmartArray3.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SmartArray
class SmartArray3
private int[] array;
private int size = 0;
private int count = 0;
public SmartArray3()
Resize(1);
public SmartArray3(int size)
this.size = size;
array = new int[this.size];
public bool Resize(int size)
try
if (array == null)
array = new int[size];
else
Array.Resize(ref array, size);
this.size++;
return true;
catch
return false;
private void add(int value)
try
if (array == null)
this.size = 1;
Resize(this.size);
array[0] = value;
this.count++;
else
if (this.count == (this.size - 1))
this.size *= 2;
this.Resize(this.size);
if ((this.count - 1) < 0)
array[0] = value;
else
array[this.count - 1] = value;
this.count++;
catch (Exception ex)
Console.Write(ex.ToString());
throw new System.IndexOutOfRangeException("Index out of Range.");
// Lock the array and add an element.
public void Add(int value)
// Request the lock, and block until it is obtained.
Monitor.Enter(array);
try
if (array == null)
this.size = 1;
Resize(this.size);
array[0] = value;
this.count++;
else
if (this.count == (this.size - 1))
this.size *= 2;
this.Resize(this.size);
if ((this.count - 1) < 0)
array[0] = value;
else
array[this.count - 1] = value;
this.count++;
finally
// Ensure that the lock is released.
Monitor.Exit(array);
// Try to add an element to the List: Add the element to the List
// only if the lock is immediately available.
public bool TryAdd(int value)
// Request the lock.
if (Monitor.TryEnter(array))
try
if (array == null)
this.size = 1;
Resize(this.size);
array[0] = value;
this.count++;
else
if (this.count == (this.size - 1))
this.size *= 2;
this.Resize(this.size);
if ((this.count - 1) < 0)
array[0] = value;
else
array[this.count - 1] = value;
this.count++;
finally
// Ensure that the lock is released.
Monitor.Exit(array);
return true;
else
return false;
public int Get(int index)
try
return array[index];
catch (IndexOutOfRangeException ex)
throw new System.IndexOutOfRangeException("Index out of range");
Code for called the Class:
private static int threadsRunning = 0;
private SmartArray3 sa = new SmartArray3();
private List<double> times;
private static string[] titles ={
"Add ", "Add failed ", "TryAdd succeeded ", "TryAdd failed "};
private static int[][] results = new int[3][];
//Event to Create Threads
private void newTest()
for (int i = 0; i < 3; i++)
Thread t = new Thread(ThreadProc);
t.Start(i);
Interlocked.Increment(ref threadsRunning);
private void ThreadProc(object state)
times = new List<double>();
DateTime finish = DateTime.Now.AddSeconds(10);
Random rand = new Random();
int[] result = { 0, 0, 0, 0};
int threadNum = (int)state;
while (DateTime.Now < finish)
Stopwatch sw = Stopwatch.StartNew();
int what = rand.Next(250);
int how = rand.Next(25);
if (how < 16)
try
sa.Add(what);
result[(int)ThreadResultIndex.AddCt] += 1;
times.Add(sw.Elapsed.TotalMilliseconds);
catch
result[(int)ThreadResultIndex.AddFailCt] += 1;
else
if (sa.TryAdd(what))
result[(int)ThreadResultIndex.TryAddSucceedCt] += 1;
else
result[(int)ThreadResultIndex.TryAddFailCt] += 1;
sw.Stop();
results[threadNum] = result;
if (0 == Interlocked.Decrement(ref threadsRunning))
StringBuilder sb = new StringBuilder(
" Thread 1 Thread 2 Thread 3 Total\n");
for (int row = 0; row < 4; row++)
int total = 0;
sb.Append(titles[row]);
for (int col = 0; col < 3; col++)
sb.Append(String.Format("{0,4} ", results[col][row]));
total += results[col][row];
sb.AppendLine(String.Format("{0,4} ", total));
Console.WriteLine(sb.ToString());
private enum ThreadResultIndex
AddCt,
AddFailCt,
TryAddSucceedCt,
TryAddFailCt
Federico Navarrete

The array that you're calling Monitor.Enter under is not always the same array that you call Monitor.Exit on. When you resize an array using Array.Resize, you pass the variable in as a reference parameter (ref). The method then creates a
new array object and assigns it to the array variable. Then, when you leave the synchronization block after resizing the array, your Monitor.Exit uses the new array rather than the one it originally entered
and... boom.
Instead of locking on the array itself, create a new private readonly field of type Object called "lock" within the SmartArray class and use that to lock on. It doesn't
need to be readonly, but the keyword will prevent you from accidentally introducing this issue again.

Similar Messages

  • I can't send emails through Yahoo using Firefox. Already contacted Yahoo and they don't know why it's happening.

    I can't send emails through Yahoo using Firefox. Already contacted Yahoo and they don't know why it's happening.
    == This happened ==
    Every time Firefox opened
    == a month agao

    I also cannot send email through Yahoo using Firefox 3.6.8. I can receive emails and surf the web just fine. I have also contacted Yahoo and have gotten no where.

  • My IPhone 5s screen turned black. I got it to turn on by holding the power and home button. I want to know why this happened to my phone?

    My IPhone 5s screen turned black. I got it to turn on by holding the power and home button. I want to know why this happened to my phone or how I can find out why it happened?

    Restore your phone!!!
    You may be wondering by now, iTunes is not detecting my phone, How do I do that?
    Answer:- Just disconnect your phone from the computer. keep Itunes open on the PC. While holding the home button of the iphone plug the phone back in. Itunes will pop a message stating it has detected a phone in recovery mode. just follow the on screen instruction then to restore your phone. If your issue is still not resolved only an Apple technician can help you

  • HT201412 My Ipad quit working - it's 2 years old.  I called Apple and they basically told me that it's done.  I can pay 249.00 to get a reburbished Ipad 1, or buy a new one.  I want to know why it died?  They mentione it could be the hard drive.

    My Ipad 1 quit working after 2 years.  Was never dropped, abused, etc.  Just quit the other night.  Went to the Apple store, called the support line and they tell me that since the warranty is up I can pay 249.00 for a refurbished Ipad or buy a new one.  Not happy at all.  I want to know why it quit.  The person I talked to at Support says he doesn't know what happened.  He says it sounds like my hard drive crashed.  ANyone else have this problem?  I am so mad.

    If the tech you talked to said anything about a "hard drive", he was completely ignorant or misspeaking rather badly. The iPads have no hard drive; the storage is all solid state. You may wish to talk to another technician, or make an appointment at an Apple Store if there's one near you, and confirm the diagnosis of a hardware failure.
    If you've confirmed that it is indeed a hardware failure, then you can pay the replacement price, find an independent iPad service shop and see if they can do a repair for less, or buy a new iPad. If it were me I would put the money toward a new, or at least newer, iPad rather than pay the replacement charge. You can get some good deals on refurbished iPad 2 and third-generation iPads from the Apple Store, any of which will run the most current versions of iOS, something which the first-gen iPad will not, and would come with a full warranty (which could be extended to two years with AppleCare).
    As to why your iPad failed, it's impossible to say with any certainty. The circuitry could have had a tiny flaw that finally failed, or the iPad could have received a static shock, something quite common in many areas in the winter when the air is dry.  Sorry it happend to you, but anything can fail.
    Regards.
    Message was edited by: varjak paw

  • Hello I want to know why am I hAving trouble logging on to craigslist

    Hello I wanted to know why am having trouble logging on to craigslist

    Hard to say without knowing what you are doing and what happens.

  • I want to know why some box of Iphone5s it's not come full accessories in box simple my iPhone 5s I have bought from Apple store last week it's first time for me use iPhone but so surprise me how the company make the phone have to use a pin to open

    I want to know why some box of Iphone5s it's not come full accessories in box simple my iPhone 5s I have bought from Apple store last week it's first time for me use iPhone but so surprise me how the company make the phone have to use a pin to open the sim but didn't give a pin inside the box and I ask staff at store their said they also don't know some box have some of are don't have a pin come together so then they told me I have to find solution or I have to buy a pin by my self I can buy it by myself but I really don't understand how come apple big company but how it's happen like this?thank you.

    Where did you purchase this. The US phones do not come with the SIM removal tool anymore. They haven't for some time now. I'm not even sure it comes with any of the devices anymore. You can just straighten out a paper clip and do the same thing.

  • When I try to turn my iPhone off, it automatically restarts itself. It has never done this before; does anyone know why it might be doing this/how to stop it happening?

    When I try to turn my iPhone off, it automatically restarts itself. It has never done this before; does anyone know why it might be doing this/how to stop it happening?

    This had happened to me today as well. I gave constantly tried resetting it, (I don't particularly want to restore it), but earlier did you find that your headphones went funny? Mine would stop playing music, but the phone would keep going. And if I paused it, and then pressed play, No sound would come out. And if I took the headphones out while it was paused it would play on the device, but as before, not through the headphones. But, I fixed it (temporarily) by pulling the headphones out while it was playing, and plugged them back it. But normally this would pause the music, and it didn't, just continued on the phone, with no sound coming out of the speakers. And it would only last for a couple of minutes and happen again. Then I tried resetting the phone, and it wouldn't turn off. Them I fixed the turn off problem by placing on a dock, and I think this also fixed the headphone problem. But then I took it off and then on the dock, and now it won't play through the dock (but it charges) and it won't turn off, again!
    Also, apples customer serivice is plainly crap. This should be easy to fix. And I shouldnt have to pay a fee to ring them up for service help.

  • I have an eight GB iPhone 3G, but when on iTunes on my Mac, it says my phone only has 6.9 GB of space total. I just want to know why this is, and if I am able to get a new phone because of malfunction.

    I have an eight (8) GB iPhone 3G, but when on iTunes on my Mac, it says my phone only has 6.9 GB of space total. I just want to know why this is, and if I am able to get a new phone because of malfunction.  Thanks!

    You don't have a malfunction.  Read this:  How Mac OS X and iOS report storage capacity, http://support.apple.com/kb/TS2419

  • I want to know why when i turn on my iPhone the screen turns white

    i want to know why when i turn on my iPhone the screen turns white

    Hello Manjanela,
    Article: TS2802 may help you with the white screen.
    Display shows a white screen
    Try turning iPhone off and then on again.
    If the iPhone will not turn off, try to reset it.
    If that doesn't work, try restoring the device.
    Have a nice day,
    Mario

  • Hai.. i want to know, why my debit card have be deducted?

    Hai.. i want to know, why payment with my debit card have be deducted?

    I'm not entirely sure what you are asking, but if it's a debit card then I don't think that they are still accepted as a valid payment method - they are not listed on this page and there have been a number of posts recently about them being declined. Do you have a credit card that you could use instead ?

  • There a lot of accounts of apple,where are many games,these accounts are sold every day,i know that only 5 person can download one app,i want to know why this accounts are not blocked

    There a lot of accounts of apple,where are many games,these accounts are sold every day,i know that only 5 person can download one app,i want to know why this accounts are not blocked

    This is not a technical question, and discussions of Apple's policies are not appropriate here. If you have some sort of problem with your own iTunes Store account, by all means let us know and we may be able to help you, but otherwise this question is not one we can discuss in these forums.
    Regards.

  • I want to know why display core dump when arch starts!

    I want to know why display core dump when arch starts!
    2008. 06 iso!
    u can see display coredump in starting......

    GAH, you silly people!
    Now I'm going to have to go off and write a program that selects a random string from a file to show on startup!
    (I'll probably fill the file with all the Arch snapshot names)
    EDIT: I should mention that you're silly because you managed to get me following a random compulsion.
    EDIT AGAIN: Done! I now get a random snapshot name in that spot whenever my system boots. I can post the script if anyone wants it, it's three lines.
    EDIT ONE LAST TIME: Oh wait, three lines and a extra file full of snapshot names.
    Last edited by arew264 (2008-07-19 02:35:05)

  • My FaceTime doesn't work for some reason, and i want to know why. ;\  It's iOS 6.1.6

    My FaceTime doesn't work for some reason, and i want to know why. >;\  It's iOS 6.1.6

    Judging by all the posts on the forum, there seems to be an issue at Apple's end, although they have made no announcement on their status page. Some users have reported that Apple is aware of the issue.
    http://www.apple.com/support/systemstatus/

  • TS3694 Hi, My iphone 5 loses the 3G connections everytime i go into tunnel and also to holland park and it does not come back untill i restart the phone? i dont know why is it happening?

    Hi, My iphone 5 loses the 3G connections everytime i go into tunnel and also to holland park and it does not come back untill i restart the phone? i dont know why is it happening?

    Hi, beth.lau.gr.
    Thank you for visiting Apple Support Communities.  
    I understand you have been experiencing issues with your iPhone restarting and showing you a blue screen.  I wont be able to give you an exact answer as to why this is happening.  However, this is the most relevant troubleshooting article for this issue.  This article also provides options to reach out to us via phone for additional assistance.  
    If your iOS device restarts, displays the Apple logo, or powers off while you're using it
    http://support.apple.com/en-us/HT203899
    Cheers, 
    Jason H.  

  • Localservice, I want to know why

    Hello! I'm user of iphone4s in Korea.
    I didn't write English well. so, please understanding.
    Do you know naver and N drive?
    The Ndrive is app and also webhard
    Um...
    I want to know why need Local services in N drive app.
    This app is just doing up&down files on the internet website.
    however, ndrive is need local service of iphone all time.
    why? Local service is what?
    why need local service any time?
    I hope to hear response of this writing
    and thanks to reading;;
    <Email Edited by Host>

    Because Apple has not negotiated an agreement to have that available in Romania.  Apple has to negotiate an agreement for each country.
    We are just users in the forum, Apple does not respond here, so we do not know why they has not negotiated the agreement.

Maybe you are looking for