如何正确地取消订阅事件

本文关键字:事件 取消 正确地 | 更新日期: 2023-09-27 18:11:38

我怎样才能正确地取消订阅一个事件,并确保被调用的方法现在不被调用?

我的问题是这种代码:

public class MyClassWithEvent
{
    public event EventHandler MyEvent;
    public int Field;
}
public class MyMainClass
{
    private MyClassWithEvent myClass;
    public void Start()
    {
        myClass.MyEvent += new EventHandler(doSomething);
    }
    public void Stop()
    {
        myClass.MyEvent -= new EventHandler(doSomething);
        myClass = null;
    }
    private void doSomething()
    {
        myClass.Field = 42;
    }
}

如果doSomething在执行的同时调用了myClass = null,指令myClass.Field = 42会因为myClass为空而抛出错误。

在设置myClass = null之前,我如何确定doSomething没有执行?

编辑:

其他的例子:

public void Stop()
{
    myClass.MyEvent -= new EventHandler(doSomething);
    // Can I add a function here to be sure that doSomething is not running ?
    myClass.Field = 101;
}

在这种情况下,我将不确定myClass.Field是42还是101。

Edit2:

显然我的问题不像我想的那么简单。我将详细说明我的情况。 我的代码是:
public class MyMainClass
{
    object camera;//can be type uEye.Camera or DirectShowCamera
    bool isRunning = false;
    public void Start()
    {
        if (camera is uEye.Camera)
        {
            camera.EventFrame += new EventHandler(NewFrameArrived);
        }
        else if (camera is DirectShowCamera)
        {
            //other init
        }
        isRunning = true;
    }
    public void Stop()
    {
        if (camera is uEye.Camera)
        {
            camera.EventFrame -= new EventHandler(NewFrameArrived);
            camera.exit;
        }
        else if (camera is DirectShowCamera)
        {
            //other stop
        }
        isRunning = false;
    }
    public void ChangeCamera(object new camera)
    {
        if (isRunning)
            Stop()
        camera = new camera();
    }
    void NewFrameArrived(object sender, EventArgs e)
    {
        uEye.Camera Camera = sender as uEye.Camera;
        Int32 s32MemID;
        Camera.Memory.GetActive(out s32MemID);
        lock (_frameCameralocker)
        {
            if (_frameCamera != null)
                _frameCamera.Dispose();
            _frameCamera = null;
            Camera.Memory.ToBitmap(s32MemID, out _frameCamera);
        }
        Dispatcher.Invoke(new Action(() =>
        {
            lock (_frameCameralocker)
            {
                var bitmapData = _frameCamera.LockBits(
                    new System.Drawing.Rectangle(0, 0, _frameCamera.Width, _frameCamera.Height),
                    System.Drawing.Imaging.ImageLockMode.ReadOnly, _frameCamera.PixelFormat);
                if (_frameCamera.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
                {
                    DeviceSource = System.Windows.Media.Imaging.BitmapSource.Create(
                                                        bitmapData.Width, bitmapData.Height, 96, 96, System.Windows.Media.PixelFormats.Gray8, null,
                                                        bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride);
                }
                _frameCamera.UnlockBits(bitmapData);
                if (OnNewBitmapReady != null)
                    OnNewBitmapReady(this, null);
            }
        }));
    }
}

当我将相机从uEye更改为directshow时,有时我会在DeviceSource = System.Windows.Media.Imaging.BitmapSource.Create(方法NewFrameArrived)中出现AccessViolationException,因为我试图从退出的相机

如何正确地取消订阅事件

创建BitmapSource

从你更新的问题来看,你唯一需要做的就是从与Dispatcher.Invoke相同的锁中锁定Stop()动作

public void Stop()
{
    lock(_frameCameralocker)
    {
        if (camera is uEye.Camera)
        {
            camera.EventFrame -= new EventHandler(NewFrameArrived);
            camera.exit;
        }
        else if (camera is DirectShowCamera)
        {
            //other stop
        }
        isRunning = false;
    }
}

这将确保所有NewFrameArrived调用在创建新相机之前完成或尚未启动。然后在调度程序内部检查您是否正在运行,以防在Stop()调用启动和完成之前帧排队。

    Dispatcher.Invoke(new Action(() =>
    {
        lock (_frameCameralocker)
        {
            if(!isRunning)
                return;
            var bitmapData = _frameCamera.LockBits(
                new System.Drawing.Rectangle(0, 0, _frameCamera.Width, _frameCamera.Height),
                System.Drawing.Imaging.ImageLockMode.ReadOnly, _frameCamera.PixelFormat);
            if (_frameCamera.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
            {
                DeviceSource = System.Windows.Media.Imaging.BitmapSource.Create(
                                                    bitmapData.Width, bitmapData.Height, 96, 96, System.Windows.Media.PixelFormats.Gray8, null,
                                                    bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride);
            }
            _frameCamera.UnlockBits(bitmapData);
            if (OnNewBitmapReady != null)
                OnNewBitmapReady(this, null);
        }
    }));

可能是Monitor的好用途?

这个想法是使用锁来确保您不会在(几乎)同一时间两次使用相同的资源:

public class MyClassWithEvent
{
    public event EventHandler MyEvent;
    public int Field;
}
public class MyMainClass
{
    private MyClassWithEvent myClass;
    private object mylock;
    public void Start()
    {
        myClass.MyEvent += new EventHandler(doSomething);
    }
    public void Stop()
    {
        myClass.MyEvent -= new EventHandler(doSomething);
        Monitor.Enter(mylock); //If somebody else already took the lock, we will wait here
        myClass = null;
        Monitor.Exit(mylock); //We release the lock, so others can access it
    }
    private void doSomething()
    {
        Monitor.Enter(mylock);
        if myClass != null
        {
            myClass.Field = 42;
        }
        Monitor.Exit(mylock);
    }
}

编辑

根据注释,Lock会是一个更好的用法(实际上是Monitor的简写):

public class MyClassWithEvent
{
    public event EventHandler MyEvent;
    public int Field;
}
public class MyMainClass
{
    private MyClassWithEvent myClass;
    private object mylock;
    public void Start()
    {
        myClass.MyEvent += new EventHandler(doSomething);
    }
    public void Stop()
    {
        myClass.MyEvent -= new EventHandler(doSomething);
        lock (mylock) //If somebody else already took the lock, we will wait here
        {
            myClass = null;
        } //We release the lock, so others can access it
    }
    private void doSomething()
    {
        lock(mylock)
        {
            if myClass != null
            {
                myClass.Field = 42;
            }
        }
    }
}

代替

myClass.Field = 42;

val local = myClass;
if (local != null)
    local.Field = 42;