我正在制作一个运行2个线程的C#程序。主要的UI线程,以及我自己创建的独立网络线程。
我已经想通了,如果我需要从网络线程中更改UI中的内容,我将需要调用一个deligate方法,它可以正常工作:
// Declared as a global variable
public delegate void ListBoxFirst();
//Then call this from the network thread
listBox1.BeginInvoke(new ListBoxFirst(InitListBox));
//Which points to this
public void InitListBox() {
listBox1.SelectedIndex = 0;
}
现在我需要能够从网络线程中读取UI值(listbox.selectedindex),但它显示错误“无法将类型'system.iasyncresult'隐式转换为'int'”如果我尝试了相同的方式(当然使用“int”而不是“void”,并且在listbox1.begininvoke之前使用“int a =”)。我已经google了很多,但我对C#很新,所以我真的迷路了。
任何帮助都会非常适合
答案 0 :(得分:1)
我明白了:
public int ReadListBoxIndex()
{
int count = 0;
listBox1.Invoke(new MethodInvoker(delegate
{
count = listBox1.SelectedIndex;
}));
return count;
}
定期调用
int count = ReadListBoxIndex();
答案 1 :(得分:0)
您需要致电EndInvoke()
以获得结果。
一些代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
listBox1.Items.AddRange(new[] { "AS","Ram"});
}
protected override void OnLoad(EventArgs e)
{
listBox1.BeginInvoke(new Action(GetResult));
}
private void GetResult()
{
if (InvokeRequired)
{
Invoke(new Action(GetResult));
}
listBox1.SelectedIndex = 0;
}
}
答案 2 :(得分:0)
这也有效,其中tn
是要添加到交叉线程的treenode,而tnret
是返回的treenode。
_treeView.Invoke(new Action(() => tnret = tn.Nodes.Add( name, name )));