2012-11-05 2 views
2

나는 데이터베이스 연결이 열려있는 연속적으로 호출되는 함수를 가지고있다. 내 문제는 한 데이터베이스 연결이 닫히기 전에 함수의 다른 인스턴스가 호출되고 데이터베이스에서 교착 상태가 발생할 수 있다는 것입니다.스레드가 C#에서 실행을 마칠 때까지 기다리는 방법?

private static WaitHandle[] waitHandles = new WaitHandle[] 
    { 
     new AutoResetEvent(false) 
    }; 

protected override void Broadcast(Data data, string updatedBy) 
    { 
     Action newAction = new Action(() => 
     { 
     DataManagerFactory.PerformWithDataManager( 
      dataManager => 
      { 
       // Update status and broadcast the changes 
       data.UpdateModifiedColumns(dataManager, updatedBy); 

       BroadcastManager.Instance().PerformBroadcast(
        data, 
        BroadcastAction.Update, 
        Feature.None); 
      }, 
      e => m_log.Error(ServerLog.ConfigIdlingRequestHandler_UpdateFailed() + e.Message)); 
      } 
     ); 

     Thread workerThread = new Thread(new ThreadStart(newAction)); 
     ThreadPool.QueueUserWorkItem(workerThread.Start, waitHandles[0]); 
     WaitHandle.WaitAll(waitHandles); 
    } 

하지만 난 스레드 오류 및 프로그램 정지를받을 :

이 나는 ​​노력했다. 그것은 내가 믿는 매개 변수가없는 스레드 시작 함수와 관련이 있습니다.

어떤 도움을 주셔서 감사합니다.

+0

QueueUserWorkItem' '의 두 번째 목적은 파라미터이다. See [MSDN] (http://msdn.microsoft.com/en-us/library/4yd16hza.aspx) – climbage

+0

일반적으로 새 스레드의'Start' 메서드를'ThreadPool'에 대기열에 넣지 않습니다. 그런 종류의 목적을 이겨내야합니다. 그냥'newAction'을 대기열에 넣으십시오. 서버 측에서 교착 상태가 발생할 수있는 측량 방법 ('PerformBroadcast'?)을 잠궈 두어야합니다. –

+0

ThreadPool.QueueUserWorkItem (newAction, null); 나던. ThreadPool.QueueUserWorkItem (newAction, waitHandles [0]); 나던. –

답변

0

이것은 완료되었습니다.

public class MyAsyncClass 
{ 

    public delegate void NotifyComplete(string message); 
    public event NotifyComplete NotifyCompleteEvent; 

    //Starts async thread... 
    public void Start() 
    { 
     System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(DoSomeJob)); 
     t.Start(); 
    } 

    void DoSomeJob() 
    { 
     //just wait 5 sec for nothing special... 
     System.Threading.Thread.Sleep(5000); 
     if (NotifyCompleteEvent != null) 
     { 
      NotifyCompleteEvent("My job is completed!"); 
     } 
    } 
} 

지금이 다른 클래스의 코드는, 첫 번째 호출 : 작업을 수행 클래스를 만듭니다

MyAsyncClass myClass = null; 


    private void button2_Click(object sender, EventArgs e) 
    { 
     myClass = new MyAsyncClass(); 
     myClass.NotifyCompleteEvent += new MyAsyncClass.NotifyComplete(myClass_NotifyCompleteEvent); 
     //here I start the job inside working class... 
     myClass.Start(); 
    } 

    //here my class is notified from working class when job is completed... 
    delegate void myClassDelegate(string message); 
    void myClass_NotifyCompleteEvent(string message) 
    { 
     if (this.InvokeRequired) 
     { 
      Delegate d = new myClassDelegate(myClass_NotifyCompleteEvent); 
      this.Invoke(d, new object[] { message }); 
     } 
     else 
     { 
      MessageBox.Show(message); 
     } 
    } 

내가 몇 가지 세부 사항을 설명 할 필요가 있다면 알려주세요. 이에

대안 BackgroudWorker이다

+0

나는 스레드가 끝날 때까지 기다리는 중이다. 나는 커스텀 클래스를 갖고 싶지 않고 Action Fired 메소드를 사용하고 싶지 않다. 스레드를 기다리는 데 대한 팁이 있습니까? 나는 아무런 조치를 취하지 않고, 단지 자식 스레드가 완료 될 때까지 아버지 스레드의 실행을 중단 시켜서 더 이상 자식 스레드가 상기 코드를 실행할 수 없도록해야한다. 코드 블록을 잠그는 것은 public static 읽기 전용 변수에서도 작동하지 않습니다. –

+0

가장 가까운 배경 작업자입니다. 그러나 몇 줄을 써야합니다. 자세한 내용을 보려면 다음 링크를 확인하십시오. http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx –

+0

내 작업에서와 같이 작동하지 않는 사용자 지정 데이터가 없습니다. 이벤트 args –