2014-03-07 90 views
0
string localConnection = 
    @"Data Source=.; Initial Catalog=Test; Uid=sa; Pwd=admin"; 
     SqlConnection c1; 

     public MainWindow() 
     { 
      InitializeComponent(); 
      c1 = new SqlConnection(localConnection); 
      SqlDependency.Start(localConnection); 
      c1.Open(); 
      SomeMethod(); 
     } 

     void SomeMethod() 
     { 
      try 
      { 
       // Assume connection is an open SqlConnection. 

       // Create a new SqlCommand object. 
       using (SqlCommand command = new SqlCommand(
        "SELECT id, name FROM dbo.tbl1", 
        c1)) 
       { 

        // Create a dependency and associate it with the SqlCommand. 
        SqlDependency dependency = new SqlDependency(command); 
        // Maintain the refence in a class member. 

        // Subscribe to the SqlDependency event. 
        dependency.OnChange += new 
         OnChangeEventHandler(OnDependencyChange); 

        // Execute the command. 
        using (SqlDataReader reader = command.ExecuteReader()) 
        { 
         // Process the DataReader. 
        } 
       } 
      } 
      catch 
      { } 
     } 

     // Handler method 
     void OnDependencyChange(object sender, 
      SqlNotificationEventArgs e) 
     { 
      Thread t = new Thread(Method1); 
      t.SetApartmentState(ApartmentState.STA); 
      t.Start(); 
      // Handle the event (for example, invalidate this cache entry). 
     } 

     void Method1() 
     { 
      Window1 obj = new Window1(); 
      obj.Show(); 
      SomeMethod(); 
     } 

在Method1()中,如果我调用obj.ShowDialog()代替obj.Show(),这将工作正常。但我需要调用obj.Show()。show method is not working on sqldependency notification,but showDialog working fine

回答

0

代码的变化将解决此问题。

Thread thread = new Thread(() => 
{ 
    Window1 w = new Window1(); 
    w.Show(); 

    System.Windows.Threading.Dispatcher.Run(); 
});