开发者

How to set value of variable in "BeginInvoke" delegate function in C#?

开发者 https://www.devze.com 2023-03-07 18:02 出处:网络
I have this code on different thread: string sub = \"\"; this.BeginInvoke((Action)(delegate() { try { sub = LISTVIEW.Items[x].Text.Trim();

I have this code on different thread:

string sub = "";

this.BeginInvoke((Action)(delegate()
{
    try
    {
        sub = LISTVIEW.Items[x].Text.Trim();
    }
    catch
    {

  开发者_如何转开发  }
}));

MessageBox.Show(sub);

what I want is to get the value of "LISTVIEW.Items[x].Text.Trim();" and pass it to "sub". please note that the LISTVIEW control is on the main thread. now how can I accomplish this?

enter code here


        Func<string> foo = () =>
            {
                try
                {
                    return LISTVIEW.Items[x].Text.Trim();
                }
                catch
                {
                     // this is the diaper anti-pattern... fix it by adding logging and/or making the code in the try block not throw
                     return String.Empty;

                }
            };

        var ar = this.BeginInvoke(foo);

        string sub = (string)this.EndInvoke(ar);

You, of course, need to be a bit careful with EndInvoke because it can cause deadlocks.

if you prefer delegate syntax you can also change

this.BeginInvoke((Action)(delegate()

to

this.BeginInvoke((Func<String>)(delegate()

you stll need to return something from all branches and call end invoke.

0

精彩评论

暂无评论...
验证码 换一张
取 消