背景线程lambda回调

时间:2015-07-21 16:25:24

标签: c#

在我的后台线程完成时,它使用匿名lambda语句运行System.Action回调。我想知道如何使用Completed函数重写下面的代码以获得callback / lambda语句。

ViewModel:BaseViewModel

public override void Initialize(System.Action onInitializeCallback = null)
{.....
    BackgroundEntityWorker.RunWorkerCompleted += (sender, args) =>
    {
        If (onInitializeCallback != null)
        {
            onInitializeCallback();
        }    
    };
.....
}

我想将其更改为以下内容

BackgroundEntityWorker.RunWorkerCompleted += BackgroundWorker_Completed =>
{
    If (onInitializeCallback != null)
    {
        onInitializeCallback();
    }    
};

BaseViewModel

public virtual void Reload(int? id = null, Action<T> callback = null)
{    
    Initialize(() =>
    {
        Localize();

        if (id == null)
        {
            IndicateLoading(false);
        }
        else
        {
            Load(id.Value, () => IndicateLoading(false));
        }
    });
}

我收到错误Argument type 'Lambda expression无法分配给参数类型System.ComponentModel.RunWorkerCompletedEventHandler

我试过

BackgroundEntityWorker.RunWorkerCompleted += BackgroundWorker_Completed;

但是我丢失了回调,如何将其设置为BackGroundWorker_Completed并维持我的回调?

1 个答案:

答案 0 :(得分:0)

BackgroundEntityWorker.RunWorkerCompleted += (sender, args) =>
{
    If (onInitializeCallback != null)
    {
        onInitializeCallback();
    }    
}

但请注意BackgroundEntityWorker null访问

public override void Initialize(System.Action onInitializeCallback = null)
{   
        If (BackgroundEntityWorker.RunWorkerCompleted != null)
        {
            BackgroundEntityWorker.RunWorkerCompleted();
        }    
}

您正在重定向两次事件。如果您展示完整的活动提升方式,那对我们来说会更容易