C# 线程访问问题

发布于 2024-11-08 13:59:55 字数 2049 浏览 0 评论 0 原文

下面的代码失败并出现错误“该进程无法访问该文件,因为该文件正在被另一个进程使用”。我很困惑到底出了什么问题。我以管理员身份运行 Visual Studio,并且没有文件在记事本中打开。

    private void Load_Click(object sender, RoutedEventArgs e)
    {
        if (txtInput.Text.Length > 1) {
            //var rootDir = System.IO.Directory.GetCurrentDirectory();
            string rootDir = @"C:\b";
            string search = txtInput.Text.Replace(" ", "");
            List<Thread> searches = new List<Thread>();

            foreach (var file in new DirectoryInfo(rootDir).GetFiles().Where(z => z.LastWriteTime > DateTime.Now.AddDays(-7))) {
                if (file.ToString().Contains(".log")) {
                    searches.Add(new Thread(new ThreadStart(() => AddDropdownItem(file.ToString(),search))));
                }
            }
            //Run ten threads at a time and wait for them to finish
            for (int i = 0; i < searches.Count; i = i + 10) {
                List<Thread> pool = new List<Thread>();
                for (int j = 0; j < 10; j++) {
                    if (i + j < searches.Count) {
                        Thread t = searches[(i + j)];
                        pool.Add(t);
                    }
                }

                foreach (Thread t in pool) {
                    t.Start();
                }

                foreach (Thread t in pool) {
                    t.Join();
                }
            }
        }
    }

    private void AddDropdownItem(string file, string search)
    {
        if (GetFileContent(file.ToString()).Contains(search)) {
            ComboBoxItem item = new ComboBoxItem();
            item.Content = file.ToString();
            Dispatcher.BeginInvoke(new ThreadStart(() => ddFiles.Items.Add(item)));
        }
    }

    private string GetFileContent(string file)
    {
        string path = System.IO.Path.Combine(@"C:\b", file);
        using (FileStream fs = new FileStream(path, FileMode.Open)) {
            return new StreamReader(fs).ReadToEnd();
        }
    }

The below code falls over with the error "The process cannot access the file because it is being used by another process". Im stumped as to whats wrong. Im running visual studio as administrator and non of the files are open in notepad .

    private void Load_Click(object sender, RoutedEventArgs e)
    {
        if (txtInput.Text.Length > 1) {
            //var rootDir = System.IO.Directory.GetCurrentDirectory();
            string rootDir = @"C:\b";
            string search = txtInput.Text.Replace(" ", "");
            List<Thread> searches = new List<Thread>();

            foreach (var file in new DirectoryInfo(rootDir).GetFiles().Where(z => z.LastWriteTime > DateTime.Now.AddDays(-7))) {
                if (file.ToString().Contains(".log")) {
                    searches.Add(new Thread(new ThreadStart(() => AddDropdownItem(file.ToString(),search))));
                }
            }
            //Run ten threads at a time and wait for them to finish
            for (int i = 0; i < searches.Count; i = i + 10) {
                List<Thread> pool = new List<Thread>();
                for (int j = 0; j < 10; j++) {
                    if (i + j < searches.Count) {
                        Thread t = searches[(i + j)];
                        pool.Add(t);
                    }
                }

                foreach (Thread t in pool) {
                    t.Start();
                }

                foreach (Thread t in pool) {
                    t.Join();
                }
            }
        }
    }

    private void AddDropdownItem(string file, string search)
    {
        if (GetFileContent(file.ToString()).Contains(search)) {
            ComboBoxItem item = new ComboBoxItem();
            item.Content = file.ToString();
            Dispatcher.BeginInvoke(new ThreadStart(() => ddFiles.Items.Add(item)));
        }
    }

    private string GetFileContent(string file)
    {
        string path = System.IO.Path.Combine(@"C:\b", file);
        using (FileStream fs = new FileStream(path, FileMode.Open)) {
            return new StreamReader(fs).ReadToEnd();
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

↘人皮目录ツ 2024-11-15 13:59:55

问题很可能与捕获 lambda 表达式中的循环变量的方式有关。请记住,闭包捕获变量,而不是。因此,基本上,AddDropdownItem 方法可能会收到与您想象的不同的参数 file 值。这是一个众所周知的行为警告 关闭循环变量

更改循环,以便将循环变量复制到单独的引用中。

foreach (var file in new DirectoryInfo(rootDir).GetFiles().Where(z => z.LastWriteTime > DateTime.Now.AddDays(-7))) 
{
  if (file.ToString().Contains(".log")) 
  {
    var capture = file;
    searches.Add(new Thread(new ThreadStart(() => AddDropdownItem(capture.ToString(),search))));
  }
}

我注意到一个潜在的不相关的问题。您似乎正在从一个工作线程创建一个 ComboBoxItem 。我确实看到您正在将添加操作编组到 UI 线程上。我会确保 ComboBoxItem 也在 UI 线程上创建,以达到良好的效果。他们的方式可能不会造成任何问题,但我会谨慎行事。我倾向于将不从 UI 线程以外的线程访问 UI 元素的规则打断到极致。

The problem is most likely with the way you are capturing the loop variable in the lambda expression. Remember, closures capture the variable, not the value. So basically the AddDropdownItem method may be receiving a different value for the parameter file than what you think it is. This is a well known behavioral caveat with closing over the loop variable.

Change the loop so that you copy the loop variable into a separate reference.

foreach (var file in new DirectoryInfo(rootDir).GetFiles().Where(z => z.LastWriteTime > DateTime.Now.AddDays(-7))) 
{
  if (file.ToString().Contains(".log")) 
  {
    var capture = file;
    searches.Add(new Thread(new ThreadStart(() => AddDropdownItem(capture.ToString(),search))));
  }
}

I noticed a potential unrelated problem. It appears that you are creating a ComboBoxItem from one of your worker threads. I do see that you are marshaling add operation onto the UI thread. I would make sure that the ComboBoxItem is also created on the UI thread for good measure. They way you have it probably will not cause any issues, but I would play it safe. I tend to interrupt the rule of no UI element access from a thread other than the UI thread to its ultimate extreme.

起风了 2024-11-15 13:59:55

我看不到“AddDropDownItem”,但我敢打赌您正在打开其中的文件,并且在线程处理完这些文件后不会关闭这些文件。释放变量(或者只是让它们超出范围并让 GC 处理它)是不够的。在线程完成之前首先显式关闭文件。

I can't see the 'AddDropDownItem' but I'll bet you're opening the file in there and not closing the files when the thread is done with them. Deallocating the variables(or just letting them fall out of scope and letting the GC handle it) isn't enough. Explicitly close the files first before the thread finishes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文