2016-01-02 63 views
1

我創建了一個組件,在我使用線程,這樣的事情:有什麼辦法從一個線程(另一個類)訪問我的組件(私有聲明)的事件嗎?

type 
    TEvent = procedure(sender:TObject) of object; 

    TMyComponent = class(TComponent) 
    protected 
    Fvar:String; 
    FMyEvent:TEvent; 
    public 
    Constructor Create(AOwner:TComponent);override; 
    published 
    property MyProperty:String read Fvar write Fvar; 
    property Event:TEvent read FMyEvent write FMyEvent; 
    end; 

    TMyThread = class(TThread) 
    procedure Execute; override; 
    end; 

implementation 

procedure TMyThread.Execute; 
begin 
    if assigned (FMyEvent) then 
    FMyEvent(Self); 
end; 

正如你所看到的,我訪問到FMyEvent這是一個私有變量,從另一個類,所以這會產生一個編譯錯誤(未聲明標識符),我知道它不合邏輯地從另一個類訪問私有變量,但我真的需要使用它!我需要在執行TMyThread時發生此事件。 我試過這段代碼:

type 
    TEvent = procedure(sender:TObject) of object; 

    TMyComponent = class(TComponent) 
    protected 
    Fvar:String; 
    FMyEvent:TEvent; 
    public 
    Constructor Create(AOwner:TComponent);override; 
    published 
    property MyProperty:String read Fvar write Fvar; 
    property Event:TEvent read FMyEvent write FMyEvent; 
    end; 
    TMyThread = class(TThread) 
    private 
    fev:TEvent; 
    protected 
    procedure Execute; override; 
    public 
    constructor Create(afev:TEvent); 
    end; 

    implementation 
    procedure TMyThread.Create(afev:TEvent);//when i call this one i send the real Event of the component. 
    begin 
    fev:=afev; 
    if assigned (FMyEvent) then 
    FMyEvent(Self);  // it works here 
    end; 

procedure TMyThread.Execute; 
begin 
if assigned (FMyEvent) then 
    FMyEvent(Self);  //IT doesn't work here 
    end; 

正如你可以看到,當我創建線程我送組件作爲參數的性能,我在兩個不同的地方稱爲事件,所以當我把它在構造函數中它運行良好,但是當我在執行過程中調用它時,什麼都不會發生!然而條件:if assigned (FMyEvent)在這兩種情況下都是如此(我嘗試了一些測試來檢查這個)。我想這個問題與「自我」有關,是否應該由另一個所有者來替換?爲什麼事件只有在創建過程中調用時才起作用?

+1

搜索[如果你想使你的應用更靈活,你可以創建一個線程的事件](http://wiki.freepascal.org/Multithreaded_Application_Tutorial#The_TThread_Class)和閱讀此頁從開始到結束小心。你會在這裏找到關於多線程的每一個信息。 – Abelisto

回答

2
  1. FMyEvent不是私人的,它是受保護的。
  2. 它也發佈爲事件如此可訪問。
  3. 您需要一個實例來訪問發佈的事件。

該錯誤未聲明標識符實際上來自第3點而不是來自可見性。

它,而應該像

procedure TMyThread.Execute; 
begin 
    if assigned (Instance.Event) then 
    Instance.Event(Self); 
end; 

或者你可以用一個事件作爲參數來創建線程。

TMyThread = class(TThread) 
private 
    FMyEvent: TEvent; 
public 
    constructor construct(ev: TEvent); 
    procedure Execute; override; 
end; 

constructor TMyThread.construct(ev: TEvent); 
begin 
    FMyEvent := ev; 
end; 

procedure TMyThread.Execute; 
begin 
    if assigned (FMyEvent) then 
    FMyEvent(Self); 
end; 
+0

你的第二個建議幫助我嘗試了一些東西,看看我的編輯。 – Safa

相關問題