顯示具有 delegate 標籤的文章。 顯示所有文章
顯示具有 delegate 標籤的文章。 顯示所有文章

2009年12月2日 星期三

C# - 多執行緒(thread)+視窗元件(form)+委派(delegate)=發生問題

在寫C#的視窗應用程式,若使用多執行緒,並用委派和事件的方式使用到視窗元件,會碰到視窗元件的資料完整性問題,例如要輸出文字到文字方塊上。此時可以在被呼叫的方法裡加上判斷條件,防範此問題。

範例的委派宣告為:
public delegate void PrintDelegate(string message);

方法應定義在擁有視窗元件的類別中:
public void PrintFuction(string str){
  if(textBox.InvokeRequired){
    this.Invoke(new PrintDelegate(str), new object[] { str });
  }else{
    textBox.Text += str;
  }
}

C# - 委派(delegate)與事件(event)

C++有函數指標,可以傳遞方法,C#則有委派可以用。

下面有範例,方法定義在類別ExecuteClass中,要呼叫方法的類別是CallClass。
public class ExecuteClass{
  public void PrintFuction(string str){
    Console.Write(str); //輸出字串
  }
}

public class CallClass{
  public delegate void PrintDelegate(string message); //宣告委派型別
  public event PrintDelegate PrintEvent; //宣告事件
  public void CallFuction(string message){
    PrintEvent(message); //呼叫委派方法
  }
}

public class MainClass{
  public static void main(){
    ExecuteClass execute = new ExecuteClass();
    CallClass call = new CallClass();
    call.PrintEvent += execute.PrintFuction; //對事件註冊方法
    call.CallFuction("呼叫成功!");
  }
}