PDA

View Full Version : مشاهده اطلاعات هم زمان با تغییر در database توسط کاربران دیگر



tara1367
دوشنبه 05 آبان 1393, 11:29 صبح
سلام خدمت دوستان گرامی
فکر میکنم این موضوع بارها سوال شده ولی متاسفانه هیچ کدوم از سورس ها و کدها لااقل به درد من نخورده.
برنامه ای که من نوشتم روی چندین کامپیوتر تحت شبکه در سطح شهر استفاده می شه. بنابراین سرعت بازیابی اطلاعات و به روز شدنش خیلی مهمه.
می خوام اگر داده ای وارد شد هم زمان دیتاگرید ویو کاربران دیگه رفرش بشه. نمی خوام از تایمر استفاده کنم چون سرعت رو خیلی پایین میاره.
ممنون میشم اگر کسی می دونه راهنمایی کنه.
با سپاس

hamid_hr
دوشنبه 05 آبان 1393, 12:06 عصر
درباره sqldependency سرچ کن منابع زیاد هستش

tara1367
چهارشنبه 07 آبان 1393, 10:44 صبح
تشکر خودم پیدا کردم . کدش رو با اندکی تغییر واسه بقیه هم می ذارم:

private void GetNames()
{
int isum = 0;
lstNames.Items.Clear();
// You must stop the dependency before starting a new one.
// You must start the dependency when creating a new one.
SqlDependency.Stop(codes.ReturnConnectionstringMsg ());
SqlDependency.Start(codes.ReturnConnectionstringMs g());
using (SqlConnection cn = new SqlConnection(codes.ReturnConnectionstringMsg()))
{
using (SqlCommand cmd = cn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Sender, Subject FROM dbo.[TMessages] WHERE RCode='" + sUCode + "' " +
"AND Result=N'خوانده نشده'";
cmd.Notification = null;
// creates a new dependency for the SqlCommand
SqlDependency dep = new SqlDependency(cmd);
// creates an event handler for the notification of data
// changes in the database.
// NOTE: the following code uses the normal .Net capitalization methods, though
// the forum software seems to change it to lowercase letters
dep.OnChange += new OnChangeEventHandler(dep_onchange);
cn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
isum++;
lstNames.Items.Add(dr.GetString(0) + " " + dr.GetString(1));
}
if (isum > 0)
{
FrmUnread fr = new FrmUnread();
fr.lblUnreadMCount.Text = "شما " + isum.ToString() + " " + "پیام خوانده نشده دارید";


if (Application.OpenForms["FrmUnread"] == null)
{
fr.Name = "FrmUnread";
fr.Show();
}
else
{
Application.OpenForms["FrmUnread"].WindowState = FormWindowState.Normal;
Application.OpenForms["FrmUnread"].Activate();
}
}
}
}
cn.Close();
cn.Dispose();
}
}




void dep_onchange(object sender, SqlNotificationEventArgs e)
{
// this event is run asynchronously so you will need to invoke to run on UI thread(if required).
if (this.InvokeRequired)
//GetNames();
lstNames.BeginInvoke(new MethodInvoker(GetNames));
else
GetNames();
// this will remove the event handler since the dependency is only for a single notification
SqlDependency dep = sender as SqlDependency;
// NOTE: the following code uses the normal .Net capitalization methods, though
// the forum software seems to change it to lowercase letters
dep.OnChange -= new OnChangeEventHandler(dep_onchange);
}