파일의 변경 사항을 확인하는 프로그램이 있습니다. 파일이 변경되면 읽음으로써 일부 레이블이 업데이트됩니다. "하지만 다른 스레드에서 스레드의 요소를 변경하려고하기 때문에 충돌이 발생합니다"~ 또는 그렇게 생각합니다. 어떤 아이디어?filesystemeventhandler에서 Form1 요소에 액세스하십시오.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
using System.IO;
using System.Threading.Tasks;
namespace RoomAutomation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void readfile_Click(object sender, EventArgs e)
{
string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Dandrews\control.txt");
FileSystemWatcher fsw = new FileSystemWatcher();
fsw.Path = @"C:\Users\Dandrews\";
fsw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite |
NotifyFilters.DirectoryName | NotifyFilters.FileName;
fsw.Changed += new FileSystemEventHandler(OnChanged);
fsw.EnableRaisingEvents = true;
if (lines[0] == "1:lights")
{
Lights.Text = "Lights are on.";
}
if (lines[0] == "0:lights")
{
Lights.Text = "Lights are off.";
}
if (lines[1] == "1:camera")
{
Camera.Text = "Camera is on.";
}
if (lines[1] == "0:camera")
{
Camera.Text = "Camera is off.";
}
if (lines[2] == "1:speakers")
{
Speakers.Text = "Speakers are on.";
}
if (lines[2] == "0:speakers")
{
Speakers.Text = "Speakers are off.";
}
if (lines[3] == "1:playlist")
{
Playlist.Text = "Playlist is on.";
}
if (lines[3] == "0:playlist")
{
Playlist.Text = "Playlist is off.";
}
}
private void OnChanged(object source, FileSystemEventArgs e)
{
Console.Write("Changes");
//Lights.Text = "New label Text";
}
}
}
`
예외는 무엇입니까? 그리고 * 왜 * 질문에 따옴표를 붙였습니까? –
@ M.Babcock 그래, ive notive 내가 당신이 그것에 반응하는 것을 볼 수 있기 전에 나는 그를 위해 빨리 그 코드를 읽었다. :) – warbio
System.Windows.Forms.dll에서 'System.InvalidOperationException'형식의 첫 번째 예외가 발생했습니다. '[6316] RoomAutomation.vshost.exe : Managed (v4.0.30319)'프로그램이 코드 0 (0x0). 인용문은 문제가 있다고 생각하는 것 주위에 있습니다. :) – Dandrews