需要帮助来通过UI线程和C#中的另一个线程获取信息 [英] Need help getting info across a UI thread and another thread in C#

查看:269
本文介绍了需要帮助来通过UI线程和C#中的另一个线程获取信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务器应用程序,可以通过网络接收信息并对其进行处理. 该服务器是多线程的,并且可以同时处理多个套接字,并且线程是通过BeginInvoke和EndInvoke样式方法在没有我的控制的情况下创建的,这些方法由相应的回调函数链接在一起.

I have a server application that receives information over a network and processes it. The server is multi-threaded and handles multiple sockets at time, and threads are created without my control through BeginInvoke and EndInvoke style methods, which are chained by corresponding callback functions.

除了主GUI外,我正在尝试创建一个表单,该表单显示一个ListBox项,该项由描述当前连接的套接字的项填充. 因此,我基本上想做的就是使用其Add()函数将一个项目添加到ListBox中,并从该线程上运行适当的回调函数. 我正在通过Controls属性访问表单控件-即:

I'm trying to create a form, in addition to the main GUI, that displays a ListBox item populated by items describing the currently connected sockets. So, what I'm basically trying to do is add an item to the ListBox using its Add() function, from the thread the appropriate callback function is running on. I'm accessing my forms controls through the Controls property - I.E:

(ListBox)c.Controls["listBox1"].Items.Add();

自然,我不只是调用该函数,我还尝试了几种在这里和网上找到的方法,可以使用delegate结合Invoke()来在线程之间进行通信,包括MethodInvoker. ,BeginInvoke()等. 似乎什么都没用,我总是遇到相同的异常,告诉我我的控件是从创建该线程的线程之外的线程访问的.

Naturally I don't just call the function, I've tried several ways I've found here and on the web to communicate between threads, including MethodInvoker, using a delegate, in combination with Invoke(), BeginInvoke() etc. Nothing seems to work, I always get the same exception telling me my control was accessed from a thread other than the one it was created on.

有什么想法吗?

推荐答案

您必须在要访问的ListBox控件上调用Invoke(或BeginInvoke),以便在创建该控件的线程上调用委托. /p>

You have to call Invoke (or BeginInvoke) on the ListBox control you are accessing in order for the delegate to be called on the thread that created that control.

ListBox listBox = c.Controls["listBox1"] as ListBox;
if(listBox != null)
{
   listBox.Invoke(...);
}

这篇关于需要帮助来通过UI线程和C#中的另一个线程获取信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆