轉帖|其它|編輯:郝浩|2011-03-07 13:54:01.000|閱讀 960 次
概述:為防止任務處理對界面操作的阻塞,用多線程進行處理是自然對用到的方法,不過也引入了跨線程操作的問題。今天碰到的問題是任務線程需要獲取和設置窗體控件的屬性,解決還是蠻容易的,引入delegate即可解決。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
為防止任務處理對界面操作的阻塞,用多線程進行處理是自然對用到的方法,不過也引入了跨線程操作的問題。今天碰到的問題是任務線程需要獲取和設置窗體控件的屬性,解決還是蠻容易的,引入delegate即可解決。
寫了一個實例程序,效果是文本框txtOutput中實時顯示文本框txtUsername和密碼框txtPassword的內容,代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
namespace WPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
/// <summary>
/// 監控線程
/// </summary>
private Thread mThread = null;
/// <summary>
/// 獲取控件文本內容的線程代理
/// </summary>
/// <param name="control">Control</param>
/// <returns>string</returns>
private delegate string GetTextHandle(Control control);
/// <summary>
/// 獲取控件文本內容
/// </summary>
/// <param name="control">Control</param>
/// <returns>string</returns>
private string GetText(Control control)
{
if (this.Dispatcher.Thread != System.Threading.Thread.CurrentThread)
{
return (string)this.Dispatcher.Invoke(new GetTextHandle(this.GetText), control);
}
else
{
if (control.GetType() == typeof(TextBox))
{
return ((TextBox)control).Text;
}
else if (control.GetType() == typeof(PasswordBox))
{
return ((PasswordBox)control).Password;
}
else
{
return string.Empty;
}
}
}
/// <summary>
/// 顯示文本的線程代理
/// </summary>
/// <param name="text">string</param>
private delegate void ShowTextHandle(string text);
/// <summary>
/// 顯示文本
/// </summary>
/// <param name="text">string</param>
private void ShowText(string text)
{
if (this.Dispatcher.Thread != System.Threading.Thread.CurrentThread)
{
this.Dispatcher.Invoke(new ShowTextHandle(this.ShowText), text);
}
else
{
this.txtOutput.Text = text;
}
}
/// <summary>
/// 監控輸入并實時顯示
/// </summary>
private void MonitorInput()
{
while (true)
{
string username = this.GetText(txtUsername);
string password = this.GetText(txtPassword);
string output = String.Format("Username:{0}, Password:{1}", username, password);
this.ShowText(output);
}
}
/// <summary>
/// 窗口內容渲染好時啟動監控線程
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Window_ContentRendered(object sender, EventArgs e)
{
mThread = new Thread(MonitorInput);
mThread.Start();
}
/// <summary>
/// 窗口關閉時結束線程
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Window_Closed(object sender, EventArgs e)
{
mThread.Abort();
}
}
}
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:網絡轉載