Reading Cell Values in Multiple Threads Simultaneously
To read cell values in more than one thread simultaneously, set Worksheet.Cells.MultiThreadReading to true. If you do not, you might get the wrong cell values.
The following code:
- Creates a workbook.
- Adds a worksheet.
- Populates the worksheet with string values.
- It then creates two threads that simultaneously read values from random cells. If the values read are correct, nothing happens. If the values read are incorrect, then a message is displayed.
If you comment this line:
testWorkbook.Worksheets[0].Cells.MultiThreadReading = true;
then the following message is displayed:
if (s != "R" + row + "C" + col)
{
MessageBox.Show("This message box will show up when cells read values are incorrect.");
}
Otherwise, the program runs without showing any message which means all values read from cells are correct.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
public static void Main() | |
{ | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
} | |
public static Workbook testWorkbook; | |
public static void ThreadLoop() | |
{ | |
Random random = new Random(); | |
while (Thread.CurrentThread.IsAlive) | |
{ | |
try | |
{ | |
int row = random.Next(0, 10000); | |
int col = random.Next(0, 100); | |
string s = testWorkbook.Worksheets[0].Cells[row, col].StringValue; | |
if (s != "R" + row + "C" + col) | |
{ | |
Console.WriteLine("This message will show up when cells read values are incorrect."); | |
} | |
} | |
catch { } | |
} | |
} | |
public static void TestMultiThreadingRead() | |
{ | |
testWorkbook = new Workbook(); | |
testWorkbook.Worksheets.Clear(); | |
testWorkbook.Worksheets.Add("Sheet1"); | |
for (var row = 0; row < 10000; row++) | |
for (var col = 0; col < 100; col++) | |
testWorkbook.Worksheets[0].Cells[row, col].Value = "R" + row + "C" + col; | |
// Commenting this line will show a pop-up message | |
// testWorkbook.Worksheets[0].Cells.MultiThreadReading = true; | |
Thread myThread1; | |
myThread1 = new Thread(new ThreadStart(ThreadLoop)); | |
myThread1.Start(); | |
Thread myThread2; | |
myThread2 = new Thread(new ThreadStart(ThreadLoop)); | |
myThread2.Start(); | |
System.Threading.Thread.Sleep(5 * 1000); | |
myThread1.Abort(); | |
myThread2.Abort(); | |
} |