複数のスレッドで同時にセル値を読み取る
Contents
[
Hide
]
複数のスレッドで同時にセル値を読み取る必要がある場合がよくあります。この記事ではその目的で Aspose.Cells の使用方法を説明します。
複数のスレッドで同時にセル値を読み取るために、Worksheet.Cells.MultiThreadReading を true に設定します。そうしないと、間違ったセル値を取得する可能性があります。
次のコード:
- ワークブックを作成します。
- ワークシートを追加します。
- 文字列値でワークシートを埋めます。
- 次に、ランダムなセルから同時に値を読み取る2つのスレッドを作成します。 読み取った値が正しい場合、何も起こりません。読み取った値が間違っている場合は、メッセージが表示されます。
この行をコメントアウトすると、次のメッセージが表示されます:
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(); | |
} |