2012-06-05 44 views
0

我得到這種類型的錯誤在下面的功能:我也有ThreadException處理,但仍然得到這樣的錯誤:線程已被中止在委託

private void tmrOneSec_Tick(object sender, EventArgs e) 
{ 
     tsSpendTime = tsSpendTime.Add(new TimeSpan(0, 0, 1)); 
     tsRemTime = tsTotalTime.Subtract(tsSpendTime); 
     if (tsRemTime.Ticks > 0) 
      clsCommonFunc.MultiThreadSetText(txtTimeRem, clsCommonFunc.GetFormattedTime(tsRemTime)); 
} 


public static void MultiThreadSetText(TextBox TxtBox, string Text) 
{ 

     if (TxtBox.InvokeRequired) 
     { 
      TxtBox.Invoke((MethodInvoker)delegate 
      { 
       MultiThreadSetText(TxtBox, Text); 
      }); 
     } 
     else 
     { 
      TxtBox.Text = Text; 
      TxtBox.Refresh(); 
     } 
} 

和錯誤是這樣的:

Source :: mscorlib 
Error :: 6/5/2012 8:51:28 AM 
Error Description : Thread was being aborted. 


Stack Trace: at System.Threading.WaitHandle.WaitOneNative(SafeWaitHandle waitHandle, UInt32 millisecondsTimeout, Boolean hasThreadAffinity, Boolean exitContext) 
at System.Threading.WaitHandle.WaitOne(Int64 timeout, Boolean exitContext) 
at System.Threading.WaitHandle.WaitOne(Int32 millisecondsTimeout, Boolean exitContext) 
at System.Windows.Forms.Control.WaitForWaitHandle(WaitHandle waitHandle) 
at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous) 
at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args) 
at System.Windows.Forms.Control.Invoke(Delegate method) 
at SE5.clsCommonFunc.MultiThreadSetText(TextBox TxtBox, String Text) 

我無法識別確切的問題。

+1

你得到的異常等待來自調用調用返回。嘗試將TxtBox.Invoke(...)更改爲TxtBox.BeginInvoke(...)。它有幫助嗎? –

+0

它的工作很好.. –

+0

我會把它變成一個答案,然後如果你不介意,所以你可以標記問題爲答案。 –

回答

1

你得到異常等待從Invoke呼叫返回。

嘗試改變

TxtBox.Invoke((MethodInvoker)delegate 
{ 
    MultiThreadSetText(TxtBox, Text); 
}); 

TxtBox.BeginInvoke((MethodInvoker)delegate 
{ 
    MultiThreadSetText(TxtBox, Text); 
}); 
1

試着改變你的委託用法像這樣:

private delegate void MultiThreadSetTextDelegate(TextBox TxtBox, string Text); 

public static void MultiThreadSetText(TextBox TxtBox, string Text) 
{ 

     if (TxtBox.InvokeRequired) 
     { 
      TxtBox.Invoke(new MultiThreadSetTextDelegate(MultiThreadSetText), TxtBox, Text); 
     } 
     else 
     { 
      TxtBox.Text = Text; 
      TxtBox.Refresh(); 
     } 
} 

嘗試的是,如果你仍然有錯誤讓我知道。但這就是我援引我的代表的方式,我根本沒有麻煩! :)