gpt4 book ai didi

c# - 如何通过异步调用更新列表框?

转载 作者:行者123 更新时间:2023-11-30 13:27:37 26 4
gpt4 key购买 nike

我开发了一个 Windows 窗体 C# 应用程序,我只想通过在不阻塞 GUI 窗体的情况下分离另一个线程来更新主窗体中列表框中的项目。由于线程无法访问像列表框这样的表单实体,我想到了使用委托(delegate)。下面的代码显示了我如何使用委托(delegate)来完成该任务,但它阻止了 GUI 表单。所以我只想将它转换为一个异步委托(delegate),它更新列表框而不阻塞 GUI 表单

委托(delegate)声明

 delegate void monitoringServiceDel();

调用委托(delegate)

new monitoringServiceDel(monitoringService).BeginInvoke(null, null);

委托(delegate)方法实现

private void monitoringService()
{
this.listEvents.Invoke(new MethodInvoker(delegate()
{
int i = 0 ;
while (i<50)
{

listEvents.Items.Add("count :" + count++);
Thread.Sleep(1000);
i ++;
}

}));


}

最佳答案

对于 Win Forms,您需要使用控件的 Invoke方法:

Executes the specified delegate on the thread that owns the control's underlying window handle

基本场景是:

类似的东西:

var bw = new BackgroundWorker();
bw.DoWork += (sender, args) => MethodToDoWork;
bw.RunWorkerCompleted += (sender, args) => MethodToUpdateControl;
bw.RunWorkerAsync();

这会让您朝着正确的方向前进。

编辑:工作样本

public List<string> MyList { get; set; }

private void button1_Click( object sender, EventArgs e )
{
MyList = new List<string>();

var bw = new BackgroundWorker();
bw.DoWork += ( o, args ) => MethodToDoWork();
bw.RunWorkerCompleted += ( o, args ) => MethodToUpdateControl();
bw.RunWorkerAsync();
}

private void MethodToDoWork()
{
for( int i = 0; i < 10; i++ )
{
MyList.Add( string.Format( "item {0}", i ) );
System.Threading.Thread.Sleep( 100 );
}
}

private void MethodToUpdateControl()
{
// since the BackgroundWorker is designed to use
// the form's UI thread on the RunWorkerCompleted
// event, you should just be able to add the items
// to the list box:
listBox1.Items.AddRange( MyList.ToArray() );

// the above should not block the UI, if it does
// due to some other code, then use the ListBox's
// Invoke method:
// listBox1.Invoke( new Action( () => listBox1.Items.AddRange( MyList.ToArray() ) ) );
}

关于c# - 如何通过异步调用更新列表框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10004613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com