U

using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HtmlSearchApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void searchButton_Click(object sender, EventArgs e)
        {
            string[] htmlFiles = Enumerable.Range(1, 1000).Select(i => $"{i:D2}.HTML").ToArray();
            string targetText = "株式情報";

            string result = await FindFirstFileContainingTextAsync(htmlFiles, targetText);

            if (result != null)
            {
                resultTextBox.Text = $"Found in file: {result}";
            }
            else
            {
                resultTextBox.Text = "Text not found in any file.";
            }
        }

        private async Task<string> FindFirstFileContainingTextAsync(string[] files, string targetText)
        {
            using (var cts = new CancellationTokenSource())
            {
                var tasks = files.Select(file => Task.Run(() => CheckFileForText(file, targetText, cts.Token), cts.Token)).ToList();

                while (tasks.Any())
                {
                    Task<string> finishedTask = await Task.WhenAny(tasks);
                    tasks.Remove(finishedTask);

                    string result = await finishedTask;
                    if (result != null)
                    {
                        cts.Cancel(); // キャンセルを通知
                        return result;
                    }
                }
            }

            return null;
        }

        private string CheckFileForText(string filePath, string targetText, CancellationToken token)
        {
            try
            {
                if (token.IsCancellationRequested)
                {
                    token.ThrowIfCancellationRequested();
                }

                string content = File.ReadAllText(filePath);
                if (content.Contains(targetText))
                {
                    return filePath;
                }
            }
            catch (OperationCanceledException)
            {
                // キャンセルされた場合は何もしない
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error reading file {filePath}: {ex.Message}");
            }

            return null;
        }
    }
}

この記事が気に入ったらサポートをしてみませんか?