在C中锁定线程#
问题描述:
在我的C#项目中,我使用Timer.One(keyboard_timer)来监视用户是否按F8,另一个Timer(剪贴板时间)是否要检查剪贴板是否包含文本。我的项目键盘始终处于启用状态,当用户按下F8键时,启用了clipboard_timer。如果用户再次按下F8键,clipboard_timer将被禁用。我的项目如何操作当用户按下F8并且他复制了一个单词时,我的项目显示在window.my程序中复制的单词在后台运行,并总是检查用户是否按F8,如果他确实如此,那么我的程序一直检查剪贴板,如果它包含文本(单词),如果它显示的含义这个词每次。 我的代码是在这里:在C中锁定线程#
在初始化
keyboard_timer.Enabled = true;
keyboard_timer.Tick += new EventHandler(keyboard_timer_Tick);
然后
public void keyboard_timer_Tick(object sender, EventArgs e)
{
// clipboard enable
if ((a % 2) != 0)
{
// F9 is for Easy mood to eanble
if ((GetAsyncKeyState(Keys.F9) == -32767) && hot_key == "F9")
{
label2.Text = "Easy";
online_clipboard_active = "";
Clipboard.Clear();
clipboard_timer.Enabled = true;
clipboard_timer.Tick += new EventHandler(clipboard_timer_Tick);
++a;
}
///// // F8 is for online Mood
else if ((GetAsyncKeyState(Keys.F8) == -32767) && online_hot_key == "F8")
{
label2.Text = "Online";
online_clipboard_active = "on";
clipboard_timer.Enabled = true;
clipboard_timer.Tick += new EventHandler(clipboard_timer_Tick);
++a;
}
}// end of enable
//clipboard disable
if ((a % 2) == 0) //
{
// F9 is for Easy mood to disable here
if ((GetAsyncKeyState(Keys.F9) == -32767) && hot_key == "F9")
{
label2.Text = "Off";
clipboard_timer.Enabled = false;
++a;
}
// F8 is for online Mood to disable here
else if ((GetAsyncKeyState(Keys.F8) == -32767) && online_hot_key == "F8")
{
label2.Text = "Off";
online_clipboard_active = "";
clipboard_timer.Enabled = false;
++a;
}
}//end of clipboard disable
}// end of keyboard timer
剪贴板计时器
public void clipboard_timer_Tick(object sender, EventArgs e)
{
if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
{
string x = Clipboard.GetText();
Clipboard.Clear();
if ((a%2)==0 && online_clipboard_active == "on")
{
//cal online_mood form to translate the string from googletranslator
online_mood o = new online_mood(x);
o.Show();
}
else if((a%2)==0 && online_clipboard_active == "")
{
//cal show_meaning form to show the meaning into a window
show_meaning s = new show_meaning(x);
s.Show();
}
}
}// end of clipboard timer Tick
我想,当剪贴板计时器上的时间键盘定时器使将被锁定,因为它们都使用变量。当剪贴板计时器运行,然后键盘计时器将被锁定,然后当剪贴板计时器完成它的作品,然后键盘计时器将被重新激活如何解决这个问题? 任何人都给我任何帮助?????
答
简单的锁定可以用静态成员完成。
private static readonly object Sync = new object();
,然后设置或获取信息使用
lock(Sync)
锁定变量之前。
顺便说一句:我没有得到你想要做的。也许你应该使用表单的Keypress事件而不是定时器。
答
查找到C# locks
你basicly做到这一点:
public Object lockObject = new Object(); //You want a separate object so that it's not changed when lock is active
...
//Code that can be run by any number of thread at the same time
...
lock(lockObject)
{
...
//Code that is accessable by only one thread at a time:
...
}
...
//Code that can be run by any number of thread at the same time
...
希望这有助于你出去了一下。
我的程序在背景上运行,并且总是检查用户是否按F8,如果他确实如此,则检查剪贴板是否包含文本(单词)如果它显示单词的含义 – DarkenShooter 2013-03-07 14:09:52