2013-06-07 2 views
0

cancellationPending없이 backgroundWorker 스레드를 중지 할 수있는 방법이 있습니까? 나는이 같은 코드를 가지고 :C# 취소없이 backgroundWorker를 실행 중지하는 방법

DoWorkFunction 
    { 
    if(worker.cancellationPending == true) return; //this works great but 

    VeryLongTimeComputingFunc();//this function take a lot of time and if it starts i can't stop it with cancellationPending 
    ...Do something 
    } 

)은 (는 VeryLongTimeComputingFunc를 시작하는 경우에도 근로자를 막을 수있는 방법이 있습니까?

답변

0

"VeryLongTimeComputingFunc"에서 "CancelWorker"이벤트를 실행하고 EventHandler에서 "worker.CancelAsync()"로 BackgroundWorker를 중지 할 수 있습니다.

이 작동합니다 :

class BackgroundClass 
    { 
    public event EventHandler CancelWorker; 

    BackgroundWorker worker = new BackgroundWorker(); 

    BackgroundClass() 
    { 
     CancelWorker += new EventHandler(BackgroundClass_CancelWorker); 
    } 

    void BackgroundClass_CancelWorker(object sender, EventArgs e) 
    { 
     worker.CancelAsync(); 
    } 

    void RunBackgroundWorker() 
    { 
     worker.DoWork += (sender, args) => 
     { 
      VeryLongTimeComputingFunction(); 
     }; 
    } 

    void VeryLongTimeComputingFunction() 
    { 
     if (CancelWorker != null) 
     { 
      CancelWorker(this, new EventArgs()); 
     } 
    } 
} 

이 당신이 VeryLongTimeComputingFunction 내부의 적절한 취소 지원을 추가 할 수 없습니다 가정하면 뭔가 "VeryLongTimeComputingFunction()"

0

을 변경할 수 있습니다 요구, 당신의 최선의 선택은이다 BGW의 스레드에 대한 참조를 저장하고 Abort을 호출하십시오. 지저분한 정리가 필요할 수 있으므로 일반적으로 권장하지 않습니다.

안전을 기하기 위해 긴 기능에서 자란 ThreadAbortedException을 잡아야합니다.

private Thread bgThread; 

void DoWorkFunction() 
{ 
    bgThread = Thread.CurrentThread; 
    try 
    { 
     VeryLongTimeComputingFunc(); 
    } 
    catch (ThreadAbortedException e) 
    { 

     //do any necessary cleanup work. 
     bgThread = null; 
    } 
} 

void CancelBGW() 
{ 
    if (bgThread != null) 
    { 
     bgThread.Abort(); 
    } 
} 

어떻게 CancelBGW가 호출 될 때와에 따라, 당신은 또한 bgThread의 할당 주위에 lock이 필요할 수 있습니다.

관련 문제