2013-02-18 65 views
-1

我試圖在任務開始前將鼠標光標更改爲Wait,完成後將其更改爲Arrow。但是,光標似乎直接從一個變爲另一個。這是我的代碼:任務完成後更改光標

this.Cursor = Cursors.Wait; 
dtResults.WriteXml(saveFileDialog.FileName); 
this.Cursor = Cursors.Arrow; 
MessageBox.Show("Exporting Complete!", "Complete!", MessageBoxButton.OK, MessageBoxImage.Information); 

有關我在做什麼錯的任何想法?

+0

dtResults.WriteXml做什麼? – cadrell0 2013-02-18 17:50:48

+0

@ cadrell0 - 這是包含在DataTable類中的方法。它將DataTable寫入XML – 2013-02-18 17:51:16

回答

2

您正在同步執行任務。所以,消息泵永遠不會真正得到等待光標的呼叫,只要用戶會看到。

要解決這個問題,您應該異步執行此操作。您可以使用Task Parallel Library,因爲你是在.NET 4.0:

this.Cursor = Cursors.Wait 
//Avoid any closure problems 
string fileName = saveFileDialog.FileName 
//Start the task of writing the xml (It will run on the next availabled thread) 
var writeXmlTask = Task.Factory.StartNew(()=>dtResults.WriteXml(fileName)); 
//Use the created task to attach what the action will be whenever the task returns. 
//Making sure to use the current UI thread to perform the processing 
writeXmlTask.ContinueWith(
    (previousTask)=>{this.Cursor = Cursors.Arrow;MessageBox.Show....}, TaskScheduler.FromCurrentSynchronizationContext()); 
+0

BeginWriteXML包含哪些內容? – 2013-02-18 17:56:15

+0

您使用的是什麼版本的.Net。假設你理解了一些異步機制,我寫了僞代碼。 .Net的版本將讓我知道如何在更多細節中展示給您 – 2013-02-18 17:58:39

+0

.NET Framework 4 :) – 2013-02-18 17:59:34

0

我的猜測是,所有這一切都是在UI線程上發生的事情。因爲DataTable.WriteXml是同步完成的,所以它會阻止用戶界面,並且不會進行更新。這就是爲什麼它看起來光標永遠不會顯示爲等待光標。

要允許UI更新並顯示等待光標,您需要將呼叫移動到dtResults.WriteXml後臺線程。我推薦使用BackgroundWorker

+0

請您詳細說明一下嗎? :) – 2013-02-18 17:59:56

+0

@DotNET有很多很多關於如何在線使用BGW的例子。你應該能夠做一些非常簡單的研究,以便找到你需要的所有東西,因爲你有一個非常簡單的用例,並且不需要使用它在最常用的描述莊園中提供的最基本的功能。 – Servy 2013-02-18 18:31:55