Cell 同时读取多个线程中的值
Contents
[
Hide
]
需要同时读取多个线程中的单元格值是一个常见的需求。本文介绍了如何为此目的使用 Aspose.Cells。
要同时读取多个线程中的单元格值,请设置工作表.Cells.多线程读取到真的.如果不这样做,您可能会得到错误的单元格值。
以下代码:
- 创建工作簿。
- 添加工作表。
- 使用字符串值填充工作表。
- 然后它创建两个同时从随机单元格中读取值的线程。 如果读取的值正确,则不会发生任何事情。如果读取的值不正确,则会显示一条消息。
如果您评论此行:
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(); | |
} |