2010-05-28 57 views
2

我尝试了以下(伪代码),但当Iam尝试阻止我的线程时,我总是遇到死锁。 问题是Join()等待线程完成,并且一个挂起的Invoke()操作也在等待完成。我该如何解决这个问题?如何正确地停止正在使用Control.Invoke的线程

Thread workerThread = new Thread(BackupThreadRunner); 
volatile bool cancel; 

// this is the thread worker routine 
void BackupThreadRunner()  
{ 
    while (!cancel) 
    { 
    DoStuff(); 
    ReportProgress(); 
    } 
} 

// main thread 
void ReportProgress() 
{ 
    if (InvokeRequired) 
    { 
     Invoke(ReportProgress); 
    } 
    UpdateStatusBarAndStuff(); 
} 

// main thread 
void DoCancel() 
{ 
    cancel=true; 
    workerThread.Join(); 
} 

回答

4

你可以使用BeginInvoke(ReportProgress) - 这样你的工作线程不必等待UpdateStatusBarAndStuff方法来完成。

1

使用`BeginInvoke的”,而不是

0

我会做一个稍微不同的方式:

private Thread workerThread; 

void StartButtonClick() 
{ 
    workerThread = new Thread(ReportProgress); 
    thread.Start(); 
} 

void CancelButtonClick() 
{ 
    // If you use a while(bool), it will repeat the task forever 
    // or with no while and just a bool, you'll have to check the value of the bool in each line 
    // so simply aborting it (providing you clean up) is accceptable. 
    workerThread.Abort(); 

    // If you don't mind your user waiting: 
    // workerThread.Join(1000); 
} 

void ReportProgress() 
{ 
    if (InvokeRequired) 
    { 
     Invoke(ReportProgress); 
     return; 
    } 

    UpdateStatusBarAndStuff(); 
} 

最佳实践的建议是 “不放弃”。这是基于你不知道中止呼叫将在什么时候退出你的代码的事实 - 它可能是创建Stream的一半。所以你最终有了一个选择:你能保证在代码退出的任何一行,它会处于合理的状态吗?如果你不能,那么你将需要使用Thread.Join()

即使使用Thread.Join,用户可能会觉得无聊并退出(ALT + F4)应用程序,并且您的情况与您在Thread.Abort()调用时的情况完全相同。

相关问题