C# 线程访问问题
下面的代码失败并出现错误“该进程无法访问该文件,因为该文件正在被另一个进程使用”。我很困惑到底出了什么问题。我以管理员身份运行 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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题很可能与捕获 lambda 表达式中的循环变量的方式有关。请记住,闭包捕获变量,而不是值。因此,基本上,
AddDropdownItem
方法可能会收到与您想象的不同的参数file
值。这是一个众所周知的行为警告 关闭循环变量。更改循环,以便将循环变量复制到单独的引用中。
我注意到一个潜在的不相关的问题。您似乎正在从一个工作线程创建一个
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 parameterfile
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.
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 theComboBoxItem
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.我看不到“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.