0

我有一个主机类,它在新线程上启动另一个类的实例,如下所示:

我正在参考这篇 MSDN 文章,根据该文章,Class2.P1 不应为空。链接:http: //msdn.microsoft.com/en-us/library/system.threading.threadstart.aspx

我错过了什么明显的东西吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            new Host().DoWork();
        }
    }
    public class Host {

      Class2Parent c = new Class2();
      Thread t;
      public void DoWork() {
      c.P1 = new Class3();
      t = new Thread(c.Start);
      t.Start();
      }
    }

    public class Class2Parent {
      public Class3 P1 = null;
        public virtual void Start() {}
    }

   public class Class2 : Class2Parent {
       public Class3 P1 = null;          
       public override void Start() {
      Console.WriteLine(P1 == null); // this is always true
      } 
   }   

   public class Class3 
   {}
}
4

1 回答 1

0

You can try to create a new thread using a timer variable just like that :

private Timer m_RequestTimer;

public void Begin()
{
            // Timer check
            if (m_RequestTimer != null)
            {
                m_RequestTimer.Change(Timeout.Infinite, Timeout.Infinite);
                m_RequestTimer.Dispose();
                m_RequestTimer = null;
            }
m_RequestTimer = new System.Threading.Timer(obj => { c.Start(); }, null, 250, System.Threading.Timeout.Infinite);
        }
}

where m_RequestTimer is an attribute of your class host and Begin a method of Host.

I hope it will help you =)

于 2013-05-17T07:51:57.267 回答