How can I access the values ​​in the user interface thread?

I have no problem invoking actions in the user interface controls through BeginInvokeand, nevertheless, to the method void. I need to get a value from a text field for use in another thread.

How can i do this?

+3
source share
3 answers

The simplest solution is to capture a local variable in the closure.

String text;
textBox.Invoke(() => text = textBox.Text);

The compiler will generate some code that is very similar to a chibacity solution - a local variable becomes the field of the class generated by the compiler.

UPDATE

- Delegate. .

internal void ExecuteOnOwningThread(this Control control, Action action)
{
    if (control.InvokeRequired)
    {
        control.Invoke(action);
    }
    else
    {
        action();
    }
}

.

String text;
textBox.ExecuteOnOwningThread(() => text = textBox.Text);

.

textBox.ExecuteOnOwningThread(() =>
{
    DoStuff();
    text = textBox.Text
    DoOtherStuff();
});

, , . - . -, , .

+4

Control.Invoke() . :

        string value = (string)this.Invoke(new Func<string>(() => textBox1.Text));

:

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
        var dlg = new Func<string>(GetText);
        string value = (string)this.Invoke(dlg);
    }
    private string GetText() {
        return textBox1.Text;
    }
+2

Invoke, , , .

    public Form1()
    {
        InitializeComponent();

        Invoke(new Action(SetTextboxTextVariable));
    }

    private string _text;

    private void SetTextboxTextVariable()
    {
        _text = txtBox.Text;
    } 

, .:)

:

    public Form1()
    {
        InitializeComponent();

        string text = GetText();
    }

    private string GetText()
    {
        string text;

        Invoke(new Action(text = txtBox.Text));

        return text;
    }
0
source

Source: https://habr.com/ru/post/1747710/


All Articles