c#-交叉线程操作无效
我在我的方法(void)上遇到异常跨线程错误,我通过以下方法解决了它们:c#-交叉线程操作无效,c#,multithreading,C#,Multithreading,我在我的方法(void)上遇到异常跨线程错误,我通过以下方法解决了它们: public delegate void onitemAdd(ListViewItem client); public void OnItemAdd(ListViewItem itemtoadd) { if (this.InvokeRequired) { onitemAdd adder = new onitemAdd(OnItemAdd); this.Invoke(adder
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;
}
}
公共委托ListViewItemReturn(客户端);
public ListViewItem OnReturnitem(客户端)
{
if(this.invokererequired)
{
ItemReturn itm=new Zserver.Form1.ItemReturn(OnReturnitem);
调用(itm,新对象[]{client});
//需要返回所调用方法的值
}
其他的
{
ListViewItem item=ClientsView.Items
.Cast()
.FirstOrDefault(x=>x.SubItems[1].Text==client.ipAddress);
退货项目;
}
}
解决方法:
object ob = this.Invoke(itm, new object[] { client });
return ob as ListViewItem;