【问题标题】:show method is not working on sqldependency notification but showDialog working fineshow 方法不适用于 sql 依赖通知,但 showDialog 工作正常
【发布时间】:2014-03-07 05:10:04
【问题描述】:
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()。

【问题讨论】:

    标签: c# .net sqldependency


    【解决方案1】:

    更改代码将解决此问题。

    Thread thread = new Thread(() =>
    {
        Window1 w = new Window1();
        w.Show();
    
        System.Windows.Threading.Dispatcher.Run();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多