使用BeginInvoke时用户界面无响应 [英] Unresponsive UI when using BeginInvoke

查看:269
本文介绍了使用BeginInvoke时用户界面无响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景
我有一个用C#编写的联网应用程序.我的服务器程序有一个UI和几个通信线程,这些线程从tcp套接字读取并在控制器UI上显示消息.

Bckground
I have a networked application written in C#. my server program has a UI and several communication threads, that read from tcp sockets and display messages on controller UI.

与每个客户端的通信是通过单独的线程完成的.当我从一个客户端收到一些消息流时,该客户端的线程在UI上写,UI是Form上的Richtextbox.

Communication with each client is done through a seprate thread. When i recieve some stream of messages from one client , the thread for that client writes on UI, which is a richtextbox on a Form.

我调用表单的SetTextHelper(string text)方法.

I call SetTextHelper(string text) method of the form.

看起来像这样

private delegate void MyTextUpdateHandler(string text);
public void SetTextHelper(string text)
{
   BeginInvoke(new MyTextUpdateHandler(SetText), new object[] { text });
}

public setText(string text)
{
   richtext.Text+= text;
}

问题
-如果我使用BeginInvoke将大量数据流写入UI时,UI完全不响应 -调用解决了这个问题,但是我读到在多线程环境中许多读取共享相同的资源调用可能导致死锁,我在大约16个线程之间共享公共ichtextbox -对我的处境有什么好处?

Question
- If i use BeginInvoke my UI is entirely unresponsive when i m writing large stream of data to UI - Invoke solves that problem, but i read that for multi threaded environment where many thereads are sharing same resource Invoke can lead to deadlocks I share the common ichtextbox between around 16 threads - What would be a good desing for my situation?

推荐答案

Invoke不应导致死锁,除非您在执行调用时拥有锁...但BeginInvoke不应造成死锁用户界面无响应.问题可能是您只是试图太频繁地更新文本框吗?也许更多缓冲传入的文本?例如,仅每半秒更新一次UI,而不要在您读取任何数据时更新.

Invoke shouldn't lead to deadlocks unless you own a lock while you're doing the invoking... but BeginInvoke shouldn't make the UI unresponsive either. Could the problem be that you're simply trying to update the textbox too often? Perhaps buffer the incoming text more? For example, only update the UI once every half second rather than any time you read any data.

这篇关于使用BeginInvoke时用户界面无响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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