在UI线程中处理WPF任务事件

时间:2014-11-11 22:05:25

标签: c# wpf multithreading events

我有一个我已经启动的任务来处理长时间运行的成像操作。在此任务中,我触发了一个自定义事件。我试图在我的MainWindow(UI线程)中订阅此事件以更新UI上的某些数据。

我发现我认为这是一个如何执行此操作的示例(Dispatcher to invoke event handler),但是得到了一个编译器错误(没有重载' Imager_CameraEvent'匹配委托' System.Action& #39;)在下面标记的点处的事件处理程序内。

欢迎对糟糕方法的建议,更正和/或警告。

主窗口:

public partial class MainWindow : Window
{   
    Imager m_imager;

    public MainWindow()
    {            
        InitializeComponent();

        m_imager = new Imager();
        m_imager.m_cameraEvent += Imager_CameraEvent;
    }


    private void RunImager_Click(object sender, RoutedEventArgs e)
    {
        // this task can create Camera Events
        Task ImagingTask = Task.Factory.StartNew(() => m_imager.StartImaging(m_cancelToken), m_cancelToken);
    }  


    void Imager_CameraEvent(object sender, CameraEventArgs e)
    {
        // Camera Events handled here
        if (this.Dispatcher.CheckAccess())
        {
            MainMessageWindow.AppendText(e.Message);
        }
        else
        {
            this.Dispatcher.BeginInvoke(new Action(Imager_CameraEvent), sender, e);  //<-- Compiler ERROR here
        }
    } 
}

Imager Class(在Task中运行方法):

public delegate void CameraEventHandler(object sender, CameraEventArgs e);

public class Imager
{

    public event CameraEventHandler m_cameraEvent;
    protected virtual void OnCameraEvent(CameraEventArgs e)
    {
        m_cameraEvent(this, e);
    }



    public async void StartImaging(CancellationToken cancelToken)
    {
        ImagingParams iParams = new ImagingParams();
        // set up iParams ...

        /// Start Imaging Task 
        Task<int> ImagingTask = Task.Factory.StartNew<int>(() => ImageReader_worker(iParams, cancelToken), cancelToken);

        try
        {
            imageCount = await ImagingTask;
        }       
        catch (OperationCanceledException)
        {
            OnCameraEvent(new CameraEventArgs("Imaging Cancelled"));
        }
        catch (Exception ex)
        {
            OnCameraEvent(new CameraEventArgs(ex.Message));
        }
        finally
        {
            ImagingTask.Dispose();
        }      
    }
}

0 个答案:

没有答案