【问题标题】:c# - Cross-thread operation not valid [duplicate]c# - 跨线程操作无效[重复]
【发布时间】:2017-04-02 08:24:39
【问题描述】:

我的方法遇到了异常跨线程错误(void),我通过以下方式解决了它们:

public delegate void onitemAdd(ListViewItem client);
public void OnItemAdd(ListViewItem itemtoadd)
{
    if (this.InvokeRequired)
    {
        onitemAdd adder = new onitemAdd(OnItemAdd);
        this.Invoke(adder, new object[] { itemtoadd });
    }
    else
    {
        if (itemtoadd != null)
        ClientsView.Items.Add(itemtoadd);
    }
}

但我不知道如何做同样的事情,但要返回返回的值:

public delegate ListViewItem ItemReturn(Client client);
public ListViewItem OnReturnitem(Client client)
{
    if (this.InvokeRequired)
    {
        ItemReturn itm = new Zserver.Form1.ItemReturn(OnReturnitem);
        this.Invoke(itm, new object[] { client });
        // need to return a value of the invoked method 
    }
    else
    {
        ListViewItem item = ClientsView.Items
         .Cast<ListViewItem>()
         .FirstOrDefault(x => x.SubItems[1].Text == client.IPadress);
        return item;
    }
}

【问题讨论】:

    标签: c# multithreading


    【解决方案1】:

    解决者:

    object ob = this.Invoke(itm, new object[] { client });
    return ob as ListViewItem;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      相关资源
      最近更新 更多