2011-01-17 3 views
2

VB.NET 2010에서 새 파일 폴더를 모니터링하는 간단한 프로그램을 작성하려고하는데 문제가 있습니다.VB.net 2010의 파일 작업 관련 문제 모니터링 디렉터리

여기 내 프로그램이 어떻게 생겼는지의 단순화 된 버전입니다 : 당신이 볼 수 있듯이

Imports System.IO 

Public Class Main 
    Public fileWatcher As FileSystemWatcher 

    Sub btnGo_Click(sender As System.Object, e As System.EventArgs) Handles btnGo.Click 
     '//# initialize my FileSystemWatcher to monitor a particular directory for new files 
     fileWatcher = New FileSystemWatcher() 
     fileWatcher.Path = thisIsAValidPath.ToString() 
     fileWatcher.NotifyFilter = NotifyFilters.FileName 
     AddHandler fileWatcher.Created, AddressOf fileCreated 
     fileWatcher.EnableRaisingEvents = True 
    End Sub 

    Private Sub fileCreated(sender As Object, e As FileSystemEventArgs) 
     '//# program does not exit when I comment the line below out 
     txtLatestAddedFilePath.Text = e.FullPath 
     '//# e.FullPath is valid when I set a breakpoint here, but when I step into the next line, the program abruptly halts with no error code that I can see 
    End Sub 
End Class 

, 내가 클릭 할 때은 FileSystemWatcher를 초기화하는 버튼이 있습니다. 초기화가 작동하고 모니터링되는 디렉토리에 새 파일을 배치하면 프로그램은 fileCreated sub에 도달합니다. e.FullPath이 올바르게 설정되어있는 것을 볼 수 있습니다. 그러나 오류 코드없이 바로 갑자기 종료됩니다 (아무 것도 볼 수 없습니다.). fileCreated sub 아웃의 모든 내용에 주석을 달면 프로그램이 예상대로 계속 실행됩니다.

내게 왜 죽어 가고있는가요? 어떤 도움이라도 대단히 감사하겠습니다. 나는 VS/VB.NET에 상당히 익숙하다. 어쩌면 나는 어리석은 실수를하고있을 뿐이다. 감사!

답변

3

스레드 간 연산 예외 일 수 있습니다.

이 시도 :

Private Sub fileCreated(sender As Object, e As FileSystemEventArgs) 
    me.Invoke(New MethodInvoker(Function() txtLatestAddedFilePath.Text = e.FullPath)) 
End Sub 

또는 (더 나은 당신의 맥락에서), fileWatcher 초기화 중 :

fileWatcher = New FileSystemWatcher() 
fileWatcher.SynchronizingObject = me 
[...] 

설명 :

http://www.blackwasp.co.uk/FileSystemWatcher.aspx (는 크로스 - 방지 참조 스레드 작업)

발췌 다음은 FileSystemWatcher 객체가 통지 이벤트를 제기 할 때 위임 호출 시스템 스레드 풀의 스레드 에 만들어진

기본적으로

. 이것은 은 일반적으로 양식을 제어하는 ​​데 사용되는 과 같은 스레드가 아닙니다. 데모 애플리케이션으로 는 리스트 박스 내용을 수정할 파일 변경 에 할당 된 스레드를 사용하여 형태의 시각적 요소 내에 기록하는 것이 필요하다 할 것이다 크로스 스레딩 동작 초래하고 IllegalOperationException는 인 던져.

+0

아하 그것은 교차 스레딩 문제였습니다. 솔루션이 완벽하게 작동했습니다. 감사합니다. –

+0

완벽 해 맥심 씨, 감사합니다 !!! – ucef