我有兩個函數ChangeText()& ChangeColor(),第一個函數名爲ChangeText誰將加載大量的數據到內存中,這將花費大量的時間,所以我運行它異步;另一個叫做ChangeColor,當數據加載好時,它會改變按鈕的顏色,所以有一個命令來運行這兩個函數:第一個是ChangeText,第二個是ChangeColor。這裏是我的代碼:爲什麼EventWaitHandle不起作用?
using System;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Threading;
using System.IO;
namespace ThreadSynchorous
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
asyncInvoke = new AsyncInvoke();
}
AsyncInvoke asyncInvoke;
EventWaitHandle waitMeHandle = new EventWaitHandle(false,EventResetMode.ManualReset);
private void button1_Click(object sender, RoutedEventArgs e)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state)
{
asyncInvoke.BeginAsync(ChangeText);
}), null);
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state)
{
asyncInvoke.BeginAsync(ChangeColor);
}), null);
label1.Content += " \r\n-------------------------\r\n";
}
private bool ChangeText()
{
waitMeHandle.Reset();
this.button1.Dispatcher.Invoke(new Func<bool>(delegate()
{
string filename = @"C:\EXO.txt";
using (StreamReader sr = new StreamReader(filename, Encoding.Default))
{
string result;
while ((result = sr.ReadLine()) != null)
{
//here perform action
}
}
label1.Dispatcher.Invoke(new Func<bool>(delegate
{
label1.Content += "Loading finish!(Thread.CurrentThreadName="+Thread.CurrentThread.ManagedThreadId.ToString()+") ";
waitMeHandle.Set();
return true;
}));
waitMeHandle.Set();
return true;
}));
waitMeHandle.Set();
return true;
}
private bool ChangeColor()
{
waitMeHandle.WaitOne();
this.button1.Dispatcher.Invoke(new Func<bool>(delegate()
{
this.button1.Background = Brushes.Red;
label1.Dispatcher.Invoke(new Func<bool>(delegate()
{
label1.Content += "Coloring finish!(Thread.CurrentThreadName="+Thread.CurrentThread.ManagedThreadId+") ";
return true;
}));
return true;
}));
return true;
}
}
}
這裏是類AsyncInvoke的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ThreadSynchorous
{
public class AsyncInvoke
{
public void BeginAsync(Func<bool> MyFunction)
{
Func<bool> func = new Func<bool>(MyFunction);
IAsyncResult iar = func.BeginInvoke(new AsyncCallback(EndAsync), func);
}
public void EndAsync(IAsyncResult iar)
{
Func<bool> func = (Func<bool>)iar.AsyncState;
func.EndInvoke(iar);
}
}
}
我擬用的EventWaitHandle同步這兩個功能,但結果是,這兩個函數將仍處於運行混亂順序:有時會首先使用ChangeText()函數,有時會首先使用ChangeColor()。我只是很困惑。
還有,我使用線程池來啓動這兩項功能,但爲什麼我得到了相同的線程ID象下面這樣:!
裝載終了(Thread.CurrentThreadName = 10)着色面漆(Thread.CurrentThreadName = 10)
我以爲Thread.CurrentThreadName會因爲我使用線程池而不同!爲什麼? thx爲您的答案。
嗨grzegorz_p,其實這是一個示例,但在實際工作中,ChangeColor函數將挑選出大量數據並與舊的txt文件進行比較,然後將數據着色爲與舊數據相同。所以在這裏我只是單獨運行該功能。 thx爲您的回覆:) – CharlieShi 2012-01-05 09:05:34
我已經做了一點調查,似乎我們有罪:) – 2012-01-05 10:02:30
我不知道你的意思。我認爲我們應該使用ThreadPool.QueueUserWorkItem(o => ChangeText()); ThreadPool.QueueUserWorkItem(o => ChangeColor());代替。 – CharlieShi 2012-01-05 14:08:34