线程正在委托中止

时间:2012-06-05 06:59:50

标签: c# multithreading

我在下面的函数中遇到这种类型的错误:我也用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)

我无法识别确切的问题。

2 个答案:

答案 0 :(得分:2)

等待从Invoke调用返回的异常。

尝试更改

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

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

答案 1 :(得分: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();
        }
} 

试试看,如果您仍然有错误,请告诉我。但这就是我如何调用我的代表而我没有任何麻烦! :)