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()。
答案 0 :(得分:0)
此问题将解决代码更改。
Thread thread = new Thread(() =>
{
Window1 w = new Window1();
w.Show();
System.Windows.Threading.Dispatcher.Run();
});