例子:
假设,我会有以下线程(请不要考虑这个例子的线程上下文执行方法中使用了什么,它只是为了解释):
type
TSampleThread = class(TThread)
private
FOnNotify: TNotifyEvent;
protected
procedure Execute; override;
public
property OnNotify: TNotifyEvent read FOnNotify write FOnNotify;
end;
implementation
procedure TSampleThread.Execute;
begin
while not Terminated do
begin
if Assigned(FOnNotify) then
FOnNotify(Self); // <- this method can be called anytime
end;
end;
然后假设,我想随时OnNotify
从主线程更改事件的方法。该主线程将事件处理程序方法实现为ThreadNotify
此处的方法:
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
FSampleThread: TSampleThread;
procedure ThreadNotify(Sender: TObject);
end;
implementation
procedure TForm1.ThreadNotify(Sender: TObject);
begin
// do something; unimportant for this example
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
FSampleThread.OnNotify := nil; // <- can this be changed anytime ?
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
FSampleThread.OnNotify := ThreadNotify; // <- can this be changed anytime ?
end;
问题:
更改可以随时从另一个线程的上下文中从工作线程调用的方法是否安全?执行上面示例中显示的操作是否安全?
我不确定,如果这绝对安全,至少因为方法指针实际上是一对指针,我不知道我是否可以将它作为原子操作。