views:

107

answers:

1

Hi All,

I have application in .net 2.0 in which I have a DataTable object globally in my application and have different dataviews in whole application.

When an action performed i have create many threads lets say 5 in which data is read from different dataview, meanwhile while 2/3 threads are reading data(not all 2 more left to read data) a thread write data in datatable. So we get exceptions like "Enumeration update" or "parameter not null" type.

I have use ReadWriteLock for this but do not find any luck it gets stop on ReaderWriterLock.AcquireWriterLock().

I do not understand where i am doing wrong.

If anyone have any idea. Please help me how to implement ReaderWriterLock for this scenario for datatable and dataview.

Thanks!!

A: 

To start with, this MSDN article might be of some help. The library that Jeffrey Richter talks about is available here.

Since the application is being developed in .Net 2.0, I recommend going for a custom ReaderWriterLock which prefers writers over readers. Also, if you are looking for some source code, then this guy might be of your help. One of the custom ReaderWriterLock, he wrote:

public sealed class ReaderWriterLock
{
    int readers = 0;
    int writers = 0;

    public void AcquireReaderLock()
    {
        Thread.BeginCriticalRegion();

        while (true)
        {
            if (Thread.VolatileRead(ref writers) == 0)
            {
                Interlocked.Increment(ref readers);

                if (Thread.VolatileRead(ref writers) == 0)
                {
                    return;
                }
                else
                {
                    Interlocked.Decrement(ref readers);
                }
            }

            Thread.Sleep(1);
        }
    }
    public void ReleaseReaderLock()
    {
        Interlocked.Decrement(ref readers);

        Thread.EndCriticalRegion();
    }
    public void AcquireWriterLock()
    {
        Thread.BeginCriticalRegion();

        while (Interlocked.CompareExchange(ref writers, 1, 0) != 0)
        {
            Thread.Sleep(1);
        }
        while (Thread.VolatileRead(ref readers) != 0)
        {
            Thread.Sleep(1);
        }
    }
    public void ReleaseWriterLock()
    {
        Thread.VolatileWrite(ref writers, 0);

        Thread.EndCriticalRegion();
    }
}

Key points:

  1. Prefers writers over readers
  2. First come first serve
  3. Spin lock used so ideal for SHORT lock-durations only
Trainee4Life