2016-04-08 38 views
0

我在關閉應用程序窗體時遇到了EAccessViolation,我不知道如何處理這個問題,我有兩個單元,這裏是主要單元的相關代碼:如何處理關閉窗體時的EAccessViolation

unit MainUnit; 
uses 
    .., myComponent1; 

implementation 
{$R *.dfm} 
procedure TForm1.Button1Click(Sender: TObject); 
begin 
    MyComponent1.doSomeWork(p1, p2, ..., pn); 
end; 
procedure TForm1.OnMyComponen1tEvent(sender: TObject; p: Integer); 
begin 
    memo1.Lines.Add(message); 
end; 
end. 

本機使用另一個單元是組件類,其中我將信號發送到memo1使用組件事件顯示過程的消息,它的東西,如:

unit myComponent; 
type 
TMyComponentEvent = procedure(sender: TObject; p: integer) of object; 
type 
TMyComponent = class(TComponent) 
// Properties and events declaration 
procedure TPThread.Execute; 
begin 
    try 
    // Create and run some worker threads 
    // Wait for them to finish the job 
    // This is the last thing to do: 
    if Assigned(FOnMyComponentEvent) then 
    begin 
     FOnMyComponentEvent(Self, p); 
    end; 
finally 
    //free ressources 
end; 
end; 

procedure TMyComponent.DoSomeWork; 
begin 
    TPThread.Create(p1, p2 ...); 
end; 
end. 

當我關閉在程序完成其工作之前的形式(線程仍在工作),我明白了這一點但有時候,沒有例外。那麼,當異常被提出時,它表示該行:memo1.Lines.Add(message);。 我不知道如何解決它,所以如何防止發生異常?

+0

他們已被銷燬後,不要訪問的對象。如果您需要如何實現這一目標的幫助,我們希望看到一些代碼。 –

回答

1

聽起來像是你不破壞形態的情況下,MyEvent事件設置爲nil,如

procedure TForm1.FormCreate(sender: TObject); 
begin 
    OtherUnit.MyEvent := MyEvent; 
end; 

procedure TForm1.FormDestroy(sender: TObject); 
begin 
    OtherUnit.MyEvent := nil; 
end; 
+0

我想我沒有提到一個重要的事情:其他單位是一個組件,MyEvent是組件事件,它有參數,我試圖不復雜我的問題,否則我會編輯我的問題,並張貼相關的代碼。 – Safa

+0

@Safa:然後編輯你的問題,並將這些高度相關的信息添加到你的問題中,而不是埋在對答案的評論中。您需要發佈一個完整的[mcve]來展示問題,而不是您發佈的完全沒有上下文的小片段。 –

+0

@Safa:如果組件位於窗體上,則不需要重置事件,因爲組件在釋放窗體時將被釋放。如果組件是在其他地方創建的,並且表單是動態分配給事件的,那麼我上面的回答仍然適用,只需用組件指針替換「OtherUnit」即可。 –

相關問題