
We recently built website software for a client that had a requirement to handle 1,000 concurrent users for 3 minutes. During the initial stress testing, the software performed perfectly up to 250 users. Once it hit 250 users, we started to receive exceptions and page content wasn't being displayed properly. After some investigation, KeyLimeTie senior developer, Michael Wick, determined the problem was around our use of the DataView class. He believed the code was not thread safe and causing threads to overwrite each other.
We went to MSDN to see if the class is thread safe and according to Microsoft, "This type is safe for multithreaded read operations. You must synchronize any write operations." What's the definition of "write operations"? In our case, the DataTable the DataView consumed was being written to once (when the website started up), but was being filtered many times in a static class. We felt the way we were using the class constituted as multiple "write operations". To confirm this, we created a test application.
Download Application only
Download Source Code
Code
In the code below, the DataView is initialized two completely different ways:
Line 4: A new instance of the DataView class is created (good)
Line 6: Uses a shared view of the DataTable (bad)
1//Create DataView
2DataView dv = null;
3if (useNew)
4 dv = new DataView(dt);
5else
6 dv = dt.DefaultView;
7
8//Apply filter
9dv.RowFilter = "RandomNumber = " + randomNumber.ToString();
10
11//Return num rows found
12return dv.Count;
With low usage, Line 4's code will work just fine. Once your software starts to pick up more usage, it will begin to error. Please run the test application we have provided to see for yourself. The screenshot below illustrates what happens when a new instance of the DataView class isn't created every time it's used. The feedback in the application shows the thread numbers and their operations. Notice the DataView code has been executed over each other's thread causing unexpected results. Next, check the "Use new keyword" checkbox and you'll see the expected results are always met (no errors reported).
Comments
|
On
4/14/2010
Dave
said:
AFAIK the setting of the RowFilter-Property on the DataView means a write operation to the DataTable too, since some indexes are created and the rows of the table are reordered. So it should help to put a lock on the table when you change the RowFilter-Property.
|
Leave a Comment