- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
很抱歉创建另一个主题,因为我的问题不具体且不准确导致线程被关闭和删除。
我有一个聊天应用程序,我希望我的应用程序不会在聊天对话的文本 block 每秒刷新一次以检索当前对话时挂起。我怎样才能防止我的应用程序每秒停止和恢复?我实际上使用了谷歌,但作为返回,我没有找到具体的答案。这是我的代码:
public MainWindow()
{
InitializeComponent();
timerChatRefresh = new DispatcherTimer();
timerChatRefresh.Interval = new TimeSpan(0, 0, 1);
timerChatRefresh.IsEnabled = false;
timerChatRefresh.Tick += new EventHandler(timerChatRefresh_Tick);
timerChatRefresh.Start();
}
void timerChatRefresh_Tick(object sender, EventArgs e)
{
ChatRefresh();
}
private void ChatRefresh()
{
conn = new MySqlConnection("Server=...; Database=...; Uid=...; Password=...;");
ds.Clear();
textBlockChatArea.Text = "";
da.SelectCommand = conn.CreateCommand();
da.SelectCommand.CommandText = "select * from chatmessagetbl";
da.SelectCommand.CommandType = CommandType.Text;
da.Fill(ds, "chatmessagetbl");
foreach (DataRow item in ds.Tables["chatmessagetbl"].Rows)
{
textBlockChatArea.Text += item["username"].ToString() + ": " + item["message"].ToString() + "\n";
}
conn.Dispose();
}
最佳答案
您需要在非 UI 线程的线程上更新文本框。
Thread chatRefreshTimer;
void StartChat()
{
chatRefreshTimer = new Thread(new ThreadStart(ChatRefresh));
chatRefreshTimer.Start();
}
void ChatRefresh()
{
conn = new MySqlConnection("Server=...; Database=...; Uid=...; Password=...;");
ds.Clear();
da.SelectCommand = conn.CreateCommand();
da.SelectCommand.CommandText = "select * from chatmessagetbl";
da.SelectCommand.CommandType = CommandType.Text;
while (true)
{
da.Fill(ds, "chatmessagetbl");
textBlockChatArea.Text = "";
foreach (DataRow item in ds.Tables["chatmessagetbl"].Rows)
{
//This has to be done on the thread that owns the textbox.
textBlockChatArea.Dispatcher.BeginInvoke(new Action(() =>
{
textBlockChatArea.Text += item["username"].ToString() + ": " + item["message"].ToString() + "\n";
}));
}
Thread.Sleep(TimeSpan.FromSeconds(1));
}
conn.Dispose();
}
我提供的代码不是很干净,它并不是你可以复制和粘贴的最终解决方案(尽管它可能会起作用),它只是试图在正确的方向上帮助你,并且向您展示一种可以使用线程完成的方法。
编辑
为了尝试澄清我在关于使用列表控件而不是文本框的评论中提出的观点,我添加了以下伪程序来尝试解释我的意思。
// Each row returned from the database will be converted in to one of these.
public class ChatEntry
{
public string UserName { get; set; }
public string Message { get; set; }
public int MessageID { get; set; }
}
// You will need to introduce a MessageID field to your database to make this method work.
public partial class MainWindow : Window
{
public ObservableCollection<ChatEntry> Entries
{
get { return (ObservableCollection<ChatEntry>)GetValue(EntriesProperty); }
set { SetValue(EntriesProperty, value); }
}
public static readonly DependencyProperty EntriesProperty = DependencyProperty.Register("Entries", typeof(ObservableCollection<ChatEntry>), typeof(MainWindow), new UIPropertyMetadata(null));
// This will be used to make sure that only new entries are added to the chat log.
int lastMessageID;
// This will be used to call UpdateEntries every second.
Thread updateThread;
public MainWindow()
{
Entries = new ObservableCollection<ChatEntry>();
InitializeComponent();
updateThread = new Thread(new ThreadStart(UpdateEntries));
updateThread.Start();
}
void UpdateEntries()
{
while (true)
{
// Prepare your query to gather messages from the message table
// with MessageID > lastMessageID.
// This bit needs to be done on the UI dispatcher or it'll cause an exception.
this.Dispatcher.BeginInvoke(new Action(() =>
{
// Each row that came back is a new message and can be added to the collection.
foreach (var row in rows)
{
Entries.Add(new ChatEntry()
{
UserName = (string)row["UserName"],
Message = (string)row["Message"],
});
}
}));
// at this point, the UI will have been upadted with JUST the new entries, no flicker
// no scrolling to the top each second.
// just one more thing, we need to set lastMessageID to be the latest messageID
// so next time UpdateEntries is called it'll only get the new ones that we don't
// have yet.
lastMessageID = Entries.Max(x => x.MessageID);
// Sleep for a second to ease the update speed.
Thread.Sleep(1000);
}
}
}
要将列表框绑定(bind)到新的 Entries 属性,您可以在 XAML 中执行类似的操作。
<Window x:Class="WpfApplication5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
>
<ListView ItemsSource="{Binding Entries}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Margin="0,0,5,0" FontWeight="Bold" />
<TextBlock Text="{Binding Message}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Window>
关于c# - 防止wpf窗口挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10980050/
我有一个应用程序,当通过 eclipse 运行时,它会导致 eclipse 本身挂起。如果我将此应用程序导出为 jar 并运行它,它工作正常。但是,如果我运行(或调试)它,应用程序将显示为启动(根据
我正在将项目从 Rails2 切换到 Rails3。我跑: rails server 服务器启动没有错误: => Booting WEBrick => Rails 3.0.7 application
当我尝试使用 XCode 打开特定项目时,它挂起。当它挂起时,它显示以下屏幕: 其他项目可以正常打开,虽然挂起的项目也打开了,意味着我什么也做不了。我的 CPU 全速运行(风扇开始运转),我必须退出多
我正在使用 BNHtmlPdfKit 将 Html 呈现为 PDF。它工作得很好,但在 iOS8 中它只是挂起 [renderer drawPageAtIndex:i inRect:renderer.
我一直在尝试在 eclipse 中创建一个项目,并且有一个名为 InitRemoteEditJob 的工作正在阻止一切。它甚至没有被取消。 请建议怎么办? 最佳答案 这个错误有很多原因。 你可以试试这
我使用这个函数来发出 cURL 请求: function curl_request($options) //single custom cURL request. { $ch = curl_i
当我尝试归档某个项目时,Xcode 无法响应。如果让他一个人呆着,他会在很长一段时间后设法打开管理器。文件在那里。如果从 library/developer/xcode/archives 中手动删除,
有时我的 Eclipse 挂起,我需要猛烈地杀死它。但是,我一直无法正确地做到这一点。似乎 kill -9 实际上并没有以正确的方式关闭它,因为我仍然可以看到挂起的窗口。什么命令序列会正确杀死我的 E
我有一个JavaFX 8应用,它有时会挂起/冻结。我觉得我已经排除了造成此问题的许多原因,但它仍在发生。 不幸的是,我无法按需复制冻结/挂起。实际上,这仅发生在(到目前为止)我同事的计算机上。它可能在
我正在尝试学习网络基础知识,并且已经从this教程构建了回显服务器。我用telnet检查了服务器,它工作正常。 现在,当我使用Internet上的许多客户端示例中的一些示例时: // Create a
我正在尝试使用 SwiftUI 实现使用 Apple 登录,但在我输入正确的密码后它挂起。 我正在使用真实用户和模拟器以及 XCode 12.0 Beta。不幸的是,我现在没有可供测试的设备。我也尝试
我包括此简单的错误处理功能来格式化错误: date_default_timezone_set('America/New_York'); // Create the error handler. fun
我正在尝试为 VisualVM 安装一些插件,但它一直卡在下面的屏幕上 - 告诉我“请等待安装程序发现插件依赖项”。我运行的是 Ubuntu 12.04。当我尝试从“可用插件”列表中安装它们时,以及当
如果堆分配/取消分配/重新分配在另一个线程中进行,DbgHelp 库的 MiniDumpWriteDump() 将挂起。这是调用堆栈:DbgHelp 暂停其他线程,然后无限期地等待这些线程获得的互斥量
我正在尝试在 Eclipse C++ 版本中安装新软件。 帮助 -> 安装新软件。当我去安装新软件时,它会挂起或需要几个小时才能移动百分比。 我读到这是 JRE7 中的一个已知错误,我假设我在安装它后
这个问题已经有答案了: process.waitFor() never returns (12 个回答) 已关闭 3 年前。 我使用以下代码运行命令: open class AppRunner {
我正在尝试为 VisualVM 安装一些插件,但它一直卡在下面的屏幕上 - 告诉我“请等待安装程序发现插件依赖项”。我正在运行 Ubuntu 12.04。当我尝试从“可用插件”列表安装它们时,以及当我
如果堆分配/取消分配/重新分配在另一个线程中进行,DbgHelp 库的 MiniDumpWriteDump() 将挂起。这是调用堆栈:DbgHelp 暂停其他线程,然后无限期地等待这些线程获得的互斥量
尝试调试竞争条件,其中我们的应用程序的轮询器线程之一永远不会返回,导致 future 的轮询器永远不会被调度。用抽象术语来说,在捕获问题时隐藏我们的业务逻辑,这就是我们的代码路径。 我们必须更新远程服
我在程序完成时遇到 Java 的 ExecutorCompletionService 问题。 我需要使用 ExecutorCompletionService 而不是 ExecutorService 因
我是一名优秀的程序员,十分优秀!