参数类型'System.Threading.SendOrPostCallback'不能赋予参数'System.Action'

时间:2013-12-15 09:19:00

标签: c# multithreading

WORKER CLASS1:

public override void Process(Crawler crawler, PropertyBag propertyBag)
            {
                SynchronizationContext uiContext = SynchronizationContext.Current;
                Thread thread = new Thread(ThreadFunc);
            }

            void ThreadFunc(object state)
            {
                var syncContext = state as SynchronizationContext;
                syncContext.Send(new Action(() => {
                    using (GeckoBrowserForm geckoBrowserForm = new GeckoBrowserForm ("http//www.google.com"))
                    {
                        geckoBrowserForm.ShowDialog();

                        while (!geckoBrowserForm.Done)
                        {
                           Application.DoEvents();
                        }

                        other code
                    }
                }), null);  
            }

但我总是得到

  

“参数'System.Action'不能分配给参数类型   'System.Threading.SendOrPostCallback'“

我希望每个Process都有自己的SynchronizationContext,然后用一些逻辑执行UIS Thread。

UI THREAD CLASS2:

protected override void OnLoad(EventArgs e)
{
  ...
  String val = "Some value";
  Done = true;
  and return back `val` to the `CLASS1` 
}

这可能吗?

2 个答案:

答案 0 :(得分:1)

来自MSDN

public virtual void Send(SendOrPostCallback d, Object state)

public delegate void SendOrPostCallback(Object state)

显然,Send方法会为代理人提供object参数和void返回值。您正在传递没有参数的委托。尝试

syncContext.Send(new Action(o => { ...

答案 1 :(得分:1)

您的SendOrPostCallback()lambda需要获取一个对象类型的参数。见the MSDN page

尝试将您的通话更改为此(请注意,lambda已从(o)更改为()):

syncContext.Send(new Action((o) => {
    using (GeckoBrowserForm geckoBrowserForm = new GeckoBrowserForm ("http//www.google.com"))
        {
            geckoBrowserForm.ShowDialog();

            while (!geckoBrowserForm.Done)
            {
                Application.DoEvents();
            }
            // other code
        }
    }), null);