同时读取多个线程中的单元格值
Contents
[
Hide
]
需要同时在多个线程中读取单元格值是一个常见的需求。本文解释了如何使用Aspose.Cells来实现这一目的。
要同时在多个线程中读取单元格值,请将 Worksheet.Cells.MultiThreadReading 设置为 true。如果不这样做,您可能会获取错误的单元格值。
以下代码:
- 创建一个工作簿。
- 添加一个工作表。
- 用字符串值填充工作表。
- 然后创建两个同时从随机单元格中读取值的线程。 如果读取的值是正确的,则不会发生任何事情。如果读取的值不正确,则会显示一条消息。
如果您注释掉这一行:
testWorkbook.Worksheets[0].Cells.MultiThreadReading = true;
那么将显示以下消息:
if (s != "R" + row + "C" + col)
{
MessageBox.Show("This message box will show up when cells read values are incorrect.");
}
否则,程序将在不显示任何消息的情况下运行,这意味着从单元格中读取的所有值都是正确的。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} |