同步线程? [英] synchronous thread ?
问题描述
我需要使用线程同时按下多个键(内循环),并在按下一秒钟后重复执行此任务.
我使用此代码,但是如果我使用加入第一个线程而不同时按下,但如果不是同时使用press但所有线程都启动,则会发现一些问题.
I need to use thread to press more than one key at same time (inner loop) and after one second press repeat this task.
I use this code but I found some problem if I use join the first thread not press at same time but if not use press at same time but all thread start.
private void play()
{
for (int i = 0; i < 2; i++)
{
Thread th=null;
for (int j = 0; j < 2;j++ )
{
SubNote sub= ArrayPlayNote[i].NotesSameTime[j];
ThreadStart starter = delegate { MessageSub(sub); };
th = new Thread(starter);
th.Start();
}
th.Join();
}
}
///////////////////////////////////////////////////////
Keyboard ky = new Keyboard();
private void MessageSub( SubNote sub)
{
ky.pianoControl1.PressPianoKey(sub.KeyNum);
Thread.Sleep(1000);
ky.pianoControl1.ReleasePianoKey(sub.KeyNum);
}
感谢您的帮助.
Thanks for help me.
推荐答案
这是因为总体思路是对线程的严重滥用.一切看起来都是错误的,无法修复.也许如果您解释了该要求,那么某人或我自己会为您提供一个简单的解决方案.这个问题看起来并不困难.
关于通过线程传递参数:请参阅我的解决方案:
如何将ref参数传递给线程 [ ^ ],
启动后更改线程(生产者)的参数 [ ^ ].
—SA
This is because the general idea is such a big misuse of threads. Everything looks wrong and beyond repair. Maybe if you explain the requirement, someone or myself would advise you a simple solution. The problem does not look very difficult.
About passing parameters through thread: see my solutions:
How to pass ref parameter to the thread[^],
change paramters of thread (producer) after it started[^].
—SA
这是基本的
this is the basic
static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
Thread t = new Thread(new ParameterizedThreadStart(MyMethod));
t.Start(i); //pass in object
}
Console.ReadLine();
}
public static void MyMethod(object input)
{
//Cast object
Console.WriteLine("Hello from MyMethod " + input.ToString());
}
因此,您可以将对象传递给线程.如果您需要从控制台到1到99(而不是现在)进行打印,则需要使用ReaderWriterLock.
好吧
如果我错了,请告诉我我正在学习.NET的人.
So you can pass in an object to thread. if you need to print in console from 1 to 99, not like now, you need to use ReaderWriterLock.
Ok.
If I am wrong tell me please someone because i am learning .NET.
这篇关于同步线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!