WPF外包就找北京動點飛揚軟體:WPF 4.5探秘之三 Dispatcher的新方法

來源:互聯網
上載者:User
 這是WPF 4.5的新特性介紹系列的第三部分。

  當你開始做的事情不同步時,Dispatcher有可能是最常用到的。因為這是從另一個線程來更新UI控制項唯一的方法。

  即使它很容易使用,WPF的團隊也為它添加了13種方法。特別是新的await keyword。在本文裡,我們將探秘這些新方法。

  新的“類”方法

  有的過載將作為一個參數Func委託。在之前的版本裡,在Dispatcher的可用方法裡無法返回一些東西(除了void),但是在新版本裡已實現了這一功能。

  這種新方法是:

  Invoke(Func)

  Invoke(Func, DispatcherPriority)

  Invoke(Func, DispatcherPriority, CancellationToken)

  Invoke(Func, DispatcherPriority, CancellationToken, TimeSpan)

  在WPF 4.5之前,返回一些東西,這段代碼應該寫為:

//The function which returns something (here of type object)
Func<object> myReturningObjectFunction = () =>
{//For example only !
return new object();
};

object returnedOject = null;

//A mock action to be abble to return the object
Action mockAction = () => { returnedOject = myReturningObjectFunction(); };

//Actually invoke the method
Dispatcher.CurrentDispatcher.Invoke(mockAction, null);

//Here I can use the returned object

  現在,您可以使用這個編寫一個更容易維持的代碼:

public void CallingMethod()
{
object returnedOject = Dispatcher.CurrentDispatcher
.Invoke(MyReturningObjectFunction, null);
}

//This method can now live alone !
private object MyReturningObjectFunction()
{
//For example only !
return new object();
}
Await-ready !

  WPF團隊已經注意到了一些新生的‘await’關鍵字,並且Dispatcher現在也可以支援這些關鍵字了。

  以下是一些新的方法:

  1. InvokeAsync(Action)

  2. InvokeAsync(Action, DispatcherPriority)

  3. InvokeAsync(Action, DispatcherPriority, CancellationToken)

  4. InvokeAsync(Func)

  5. InvokeAsync(Func, DispatcherPriority)

  6. InvokeAsync(Func, DispatcherPriority, CancellationToken)

  這些方法返回DispatcherOperation / DispatcherOperation類型的對象。然後您就可以在它本身或者是“Task”屬性裡使用await關鍵字。

  下面舉個例子:

public async void CallingMethod()
{
await Dispatcher.CurrentDispatcher.InvokeAsync(MyReturningObjectFunction);
}

最後將會出現一個內容為“Calling Task.Wait will result in a deadlock if the operation is queued on a calling thread. For more information about using a Task to perform asynchronous operations, see Task Parallelism (Task Parallel Library).”的免責申明/警告。

Cancellation

最後,您可能已經注意到CancellationToken類型的新參數。這是.NET 4 Cancellation Framework的一部分。在後台中,Dispatcher操作將開始建立一個受到這個取消指令的管理Task對象。

如果Task沒有啟動即你的發送器操作沒有啟動,那麼它將不再啟動。如果它已經開始那麼它不會被停止,並且繼續執行。

事實上,取消指令的停止與否完全取決於任務本身的運轉。然而,我沒有為給定的Action找到一種方法跳過Cancellation指令,而不再使用在第一段中關於返回對象提到過的相同的方法。

並沒有一定要使用取消指令的情境,但是我認為這是使非同步關鍵字的工作的必要條件。

這種情況在demo中很難複製,但是我們還找到了一個工作例子:

//Create a token source
var cts = new CancellationTokenSource();

//Launch the cancel of the token
Task.Factory.StartNew(() => cts.Cancel());

//Launch an operation with priority normal
// this will delay the execution of the following Invoke call.
Dispatcher.BeginInvoke(new Action(() =>
{
int i = 0; while (i < 300)
//Update the UI to be sure to block the following
// action. Rendering will occur and takes precedence
{ i++; _counterTextBlock.Text = i.ToString(); }
}), null);

try
{
//Launch a task with the cancellation token
Dispatcher.Invoke(() => { while (true);},
DispatcherPriority.Background, cts.Token);
}
catch (OperationCanceledException ex)
{
//We are here because the token was cancelled
Console.WriteLine("The operation didn't even start !");
}

Bonus

另外還有兩個更容易使用的方法:

1. Invoke(Action)

2. Invoke(Action, DispatcherPriority, CancellationToken, TimeSpan) 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.