2016-08-19 47 views
-1

我使用了一个约束的执行区域(CER)保护的代码部分线程的while循环中:如何跳出循环中只包含一个约束的执行区域(CER)

private static void MyThreadFunc() 
{ 
    try { 
     ... 
     while (true) 
     { 
      RuntimeHelpers.PrepareConstrainedRegions(); 
      try { } 
      finally 
      { 
       // do something not to be aborted 
      } 
      Thread.Sleep(1); // allow while loop to be broken out 
     } 
    } 
    catch (ThreadAbortException e) 
    { 
     // handle the exception 
    } 
} 

问题是如果我在while循环结束时没有引入Thread.Sleep(1)语句,则线程上任何调用Thread.Abort()的尝试都会挂起。有没有更好的方法可以在不使用Thread.Sleep()函数的情况下中止线程?

回答

0

我不知道为什么你需要手动中止这个线程,因为一旦CLR完成或者使用Thread.Join来等待它终止,CLR就会这样做。但你可以利用ManualResetEvent优雅地放弃它。

我已经通过更换而作出的代码一些变化(真)ManualResetEvent

class ThreadManager 
{ 
    private ManualResetEvent shutdown = new ManualResetEvent(false); 
    private Thread thread; 

    public void start() 
    { 
     thread = new Thread(MyThreadFunc); 
     thread.Name = "MyThreadFunc"; 
     thread.IsBackground = true; 
     thread.Start(); 
    } 

    public void Stop() 
    { 
     shutdown.Set(); 
     if (!thread.Join(2000)) //2 sec to stop 
     { 
      thread.Abort(); 
     } 
    } 

    void MyThreadFunc() 
    { 
     while (!shutdown.WaitOne(0)) 
     { 
      // call with the work you need to do 
      try { 
        RuntimeHelpers.PrepareConstrainedRegions(); 
        try { } 
        finally 
        { 
         // do something not to be aborted 
        } 
       } 
       catch (ThreadAbortException e) 
       { 
         // handle the exception 
       } 
     } 
    } 
}