Cross-thread operation not valid и Win Form - C#
Формулировка задачи:
Здравствуйте! Возникла необходимость, да и просто человеческое желание изучить C#, создать небольшую программу, которая бы выполняла роль некоего проводника. Отображала папки из ПК находящихся в локальной сети и выполняла функции слежения в реальном времени (т.е. при удалении/появлении файлов список LIstView соответствующие обновлялся).
Когда задаётся папка для слежения - все хорошо, но как только происходит какое-то событие FileSystemWatcher, то возникает "Cross-thread operation not valid" (см. первую фотку)
Уже всякие способы перепробовал.... ничего... не хватает уровня знаний
Может я что-то не так делаю или хочу не исполнимое?...
Заранее спасибо!
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using Microsoft.CSharp;
using System.Xml;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
namespace Explorer_main
{
public partial class UserControl1 : UserControl
{
string folderName1;
// delegate void ShowListViewSafe(string _str);
// private Thread lvThread = null;
public UserControl1()
{
folderName1 = "C:\\";
InitializeComponent();
}
private void ShowListView(string _str)
{
//listView1.Items.Clear();
string[] dirInfo = Directory.GetFileSystemEntries(_str);
foreach (string fileF in dirInfo)
{
listView1.Items.Add(fileF, System.IO.Path.GetFileName(fileF), 0);
}
textBox3.Text = listView1.Items.Count.ToString();
}
private void button3_Click(object sender, EventArgs e)
{
folderBrow.ShowDialog();
folderName1 = folderBrow.SelectedPath;
textBox1.Text = folderName1;
ShowListView(folderName1);
WatchFolfer(folderName1);
}
private void backWork_DoWork(object sender, DoWorkEventArgs e)
{
string _str;
_str = (string)e.Argument;
MessageBox.Show(_str);
if (listView1.InvokeRequired)
{
MessageBox.Show("свой поток");
}
else
MessageBox.Show("поток из вне...");
listView1.Items.Clear();
string[] dirInfo = Directory.GetFileSystemEntries(_str);
foreach (string fileF in dirInfo)
{
listView1.Items.Add(fileF, System.IO.Path.GetFileName(fileF), 0);
}
textBox3.Text = listView1.Items.Count.ToString();
}
#region Модуль слижения за папками на появление и удаления файлов
private void WatchFolfer(string sPach)
{
_watchFolder = new FileSystemWatcher();
_watchFolder.Path = sPach;
//MessageBox.Show("Слежение "+_watchFolder.Path);
_watchFolder.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
_watchFolder.Changed += new FileSystemEventHandler(_watchFolder_Changed);
_watchFolder.Created += new FileSystemEventHandler(_watchFolder_Created);
_watchFolder.Deleted += new FileSystemEventHandler(_watchFolder_Deleted);
_watchFolder.Renamed += new RenamedEventHandler(_watchFolder_Renamed);
_watchFolder.Disposed += new EventHandler(_watchFolder_Disposed);
_watchFolder.EnableRaisingEvents = true;
}
void _watchFolder_Disposed(object sender, EventArgs e)
{
}
void _watchFolder_Renamed(object sender, RenamedEventArgs e)
{
}
void _watchFolder_Deleted(object sender, FileSystemEventArgs e)
{
//MessageBox.Show("Deleted " + e.FullPath);
//ShowListView(folderName1);
backWork.RunWorkerAsync(folderName1);
}
void _watchFolder_Created(object sender, FileSystemEventArgs e)
{
MessageBox.Show("create "+e.FullPath);
//ShowListView(folderName1);
backWork.RunWorkerAsync(folderName1);
}
private void _watchFolder_Changed(object sender, FileSystemEventArgs e)
{
}
#endregion
}
}Решение задачи: «Cross-thread operation not valid и Win Form»
textual
Листинг программы
...... fileSystemWatcher1.EnableRaisingEvents = false; ShowListView(folderName1); fileSystemWatcher1.Path = folderName1; fileSystemWatcher1.EnableRaisingEvents = true; .......