FireandForget委托 - c#

时间:2010-04-30 19:16:38

标签: c#

我遇到了这个链接link text

在文章中,作者有这个方法的定义

static void WriteIt(string first, string second, int num)

我在测试应用中将其更改为

static void WriteIt(CustomerObject Customer)
{
  fileIO.CreateFile(XMLUtil.Serialize(Customer));
}

哪里

 public static string Serialize(object o)
    {
        System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
        ns.Add("", "");

        return Serialize(o, ns);

    }

    public static string Serialize(object o, XmlSerializerNamespaces ns)
    {
        try
        {
            using (System.IO.MemoryStream m = new System.IO.MemoryStream())
            {

                //serialize messagelist to xml
                XmlSerializer serializer = new XmlSerializer(o.GetType(), "");

                if (ns != null)
                    serializer.Serialize(m, o, ns);
                else
                    serializer.Serialize(m, o);

                m.Position = 0;
                byte[] b = new byte[m.Length];
                m.Read(b, 0, b.Length);

                return System.Text.UTF8Encoding.UTF8.GetString(b);
            }
        }
        catch (Exception ex)
        {
            return "Ex = " + ex.ToString();
        }
    }

此方法始终提供异常

static void EndWrapperInvoke (IAsyncResult ar)
    {
        wrapperInstance.EndInvoke(ar); 
        ar.AsyncWaitHandle.Close();
    }

堆栈跟踪:

服务器堆栈跟踪:

   at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at System.Delegate.DynamicInvoke(Object[] args)
   at SRC.FileMover.ThreadUtil.InvokeWrappedDelegate(Delegate d, Object[] args)
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.PrivateProcessMessage(RuntimeMethodHandle md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage msg, IMessageSink replySink)

Exception rethrown at [0]: 
   at System.Runtime.Remoting.Proxies.RealProxy.EndInvokeHelper(Message reqMsg, Boolean bProxyCase)
   at System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(Object NotUsed, MessageData& msgData)
   at SRC.FileMover.ThreadUtil.DelegateWrapper.EndInvoke(IAsyncResult result)
   at SRC.FileMover.ThreadUtil.EndWrapperInvoke(IAsyncResult ar)
   at System.Runtime.Remoting.Messaging.AsyncResult.SyncProcessMessage(IMessage msg)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage msg, IMessageSink replySink)
   at System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.DoAsyncCall()
   at System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.ThreadPoolCallBack(Object o)
   at System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(_ThreadPoolWaitCallback tpWaitCallBack)
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state)

更新1: 试图运行我的应用程序并获得完整的例外。它似乎发生在不同的地方。我会转发我的?很快。我认为如果我可以发布我的申请可能是明智的。我可以上传.zip文件,还是发布我正在使用的.cs代码更好?

2 个答案:

答案 0 :(得分:3)

如果你想解雇并忘记一个方法,你应该使用ThreadPool:

ThreadPool.QueueUserWorkItem(o => SomeMethod(someParameter), null);

答案 1 :(得分:0)

如果您只想解雇并忘记某个方法,为什么不直接使用Action声明一个匿名方法?

Action<CustomerObject> fireAndForget = delegate(CustomerObject obj) 
{
     fileIO.CreateFile(XMLUtil.Serialize(obj));
};

fireAndForget.BeginInvoke(new CustomerObject()); // Don't need to End Invoke