如何在另一个线程运行时禁用文本框

时间:2013-06-16 11:29:50

标签: java multithreading

我想在线程运行时禁用文本框。线程执行完成后,应启用表单上的文本框。

CODE

Thread thread = new Thread(new ThreadStart(ScannerThreadFunction));
thread.Start();

    public void ScannerThreadFunction()
    {            
        try
        {
            Scan();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
        }
    }

在Scan()运行之前,应禁用TextBox。 scan()完成后,我想启用TextBox。

2 个答案:

答案 0 :(得分:2)

在WPF中,您可以在扫描方法中执行此操作。您只需将TextBox的启用和禁用推送到UI线程,然后您就像调度员那样执行此操作:

private void button1_Click(object sender, RoutedEventArgs e)
{
    var thread = new Thread(new ThreadStart(ScannerThreadFunction));
    thread.Start();
}

public void ScannerThreadFunction()
{
    try
    {
        Scan();
    }
    catch (Exception ex)
    {
        //Writing to the console won't be so useful on a desktop app
        //Console.WriteLine(ex.Message);
    }
    finally
    {
    }
}

private void Scan()
{
    Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal,
                                          new Action(() => MyTextbox.IsEnabled = false));

    //do the scan

    Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal,
                              new Action(() => MyTextbox.IsEnabled = true));
}

在WinForms中,您也可以在扫描方法中执行此操作,但执行方式略有不同。您需要检查表单上的InvokeRequired布尔值是否为true,如果是,请使用MethodInvoker,如下所示:

private void button1_Click(object sender, EventArgs e)
{
    var thread = new Thread(new ThreadStart(ScannerThreadFunction));
    thread.Start();
}

public void ScannerThreadFunction()
{
    try
    {
        Scan();
    }
    catch (Exception ex)
    {
        //Writing to the console won't be so useful on a desktop app
        //Console.WriteLine(ex.Message);
    }
    finally
    {
    }
}

private void Scan()
{
    ChangeTextBoxIsEnabled(false);

    //do scan

    ChangeTextBoxIsEnabled(true);
}

private void ChangeTextBoxIsEnabled(bool isEnabled)
{
    if (InvokeRequired)
    {
        Invoke((MethodInvoker)(() => MyTextbox.Enabled = isEnabled));
    }
    else
    {
        MyTextbox.Enabled = isEnabled;
    }
}

答案 1 :(得分:0)

在开始后台线程之前 - 禁用文本框。在后台线程中,在处理完成时通知主线程(如果您正在使用WPF,请使用主线程的Dispatcher),并在主线程中再次启用文本框。