[WPF] Error : Parameter count mismatch (使用Dispatcher請注意)

  • 1343
  • 0
  • 2014-01-08

摘要:[C#] Parameter count mismatch (dispatcher)

那天在使用dispatcher.BeginInvoke時 產生一個 Error : Parameter count mismatch

code大概如下就會出現此錯誤


 public void FunA()
 {            
      int[] Array = new int[3] { 0, 1, 2 };
      Dispatcher.BeginInvoke(new FuncDelegate(Function), Array);
 }

 private delegate void FuncDelegate(int[] Array);
 private void Function(int[] Array)
 {
      //something...
 }

查了MSDN

public DispatcherOperation BeginInvoke(
	Delegate method,
	params Object[] args
)

或許你就會有頭緒, 主要為args這個參數... 用法並非如此使用

params 關鍵字可使您指定可以接受引數的方法參數,其中引數數目是可變的。  (sample code可以查一下MSDN好朋友XD)

 

很明顯...解法或許就是把arrary 拆開, 一個一個放進去...


int[] Array = new int[3] { 0, 1, 2 };
Dispatcher.BeginInvoke(new FuncDelegate(Function), Array[0], Array[1], Array[2]);

 

但聰明點, 就用一個object變數包裝整個array囉 (記得Function內的實作, 需將obj再轉回 int[])


int[] Array = new int[3] { 0, 1, 2 };
object obj = Array;
Dispatcher.BeginInvoke(new FuncDelegate(Function), obj);

 

================另外補充=================

以往C++是透過 postMessage/sendMessage去讓UI進行更新

但C#中 您可採用 Dispatcher去實現  (要在C#採用postMessage也是可以, 就引入user32.dll)

而Dispatcher.Invoke相當於sendMessage,  Dispatcher.BeginInvoke則相當於postMessage

 

 

 

任何問題或建議, 歡迎一起討論:)