我創建了一個組件,在我使用線程,這樣的事情:有什麼辦法從一個線程(另一個類)訪問我的組件(私有聲明)的事件嗎?
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)
在這兩種情況下都是如此(我嘗試了一些測試來檢查這個)。我想這個問題與「自我」有關,是否應該由另一個所有者來替換?爲什麼事件只有在創建過程中調用時才起作用?
搜索[如果你想使你的應用更靈活,你可以創建一個線程的事件](http://wiki.freepascal.org/Multithreaded_Application_Tutorial#The_TThread_Class)和閱讀此頁從開始到結束小心。你會在這裏找到關於多線程的每一個信息。 – Abelisto