Reputation: 69
I have a C# program to winform application. It is intended as a memory game. First I have to show a matrix with number of values inside it. say 3 or 4. I have to pause the matrix for a while so that user saves it in his memory. For that I use thread1. Then I need to blank the matrix and show some options on the right panel of form. It is done using Thread2. The problem now is actually thread2 is executed first. Can anyone help me please.I am new to C#...
Thread Thread1 = new Thread(new ParameterizedThreadStart(invokedisplaymatrix));
Thread1.IsBackground = true;
Thread1.Start(MatrixInfoValues);
Thread Thread2 = new Thread(new ThreadStart(invokedisplayblankmatrix));
Thread2.IsBackground = true;
Thread2.Start();
}
private void invokedisplaymatrix(object indx)
{
Invoke(new displaymatrixdelegate(displaymatrix),new object[] {indx});
Thread.sleep(5000);
}
private void invokedisplayblankmatrix()
{
Invoke(new displayblankmatrixdelegate(displayblankmatrix));
}...
.. public delegate void displaymatrixdelegate(int[] ind1);
public delegate void displayblankmatrixdelegate();
}//end of main form
Upvotes: 0
Views: 1214
Reputation: 4501
Look at System.Threading.Semaphore:
in this sample we need to run "work2" delegate fisrt:
static void Main(string[] args)
{
var sem = new Semaphore(0, 1);
Action<object> work1 = o =>
{
sem.WaitOne();
Console.WriteLine("enter " + o);
Thread.Sleep(2000);
Console.WriteLine("exit " + o);
};
Action<object> work2 = o =>
{
Console.WriteLine("enter " + o);
Thread.Sleep(2000);
Console.WriteLine("exit " + o);
sem.Release();
};
work1.BeginInvoke("first", ar => { }, null);
work2.BeginInvoke("second", ar => { }, null);
Console.ReadKey();
}
Upvotes: 0
Reputation: 5833
You should use AutoResetEvent to implement it.
So...
var sync = new AutoResetEvent();
var thread1 = new Thread(new ParameterizedThreadStart(invokedisplaymatrix));
thread1.IsBackground = true;
thread1.Start(MatrixInfoValues);
thread Thread2 = new Thread(new ThreadStart(invokedisplayblankmatrix));
thread2.IsBackground = true;
thread2.Start();
private void invokedisplaymatrix(object indx)
{
Invoke(new displaymatrixdelegate(displaymatrix),new object[] {indx});
Thread.sleep(5000);
sync.Set();
}
private void invokedisplayblankmatrix()
{
sync.Wait();
Invoke(new displayblankmatrixdelegate(displayblankmatrix));
}
But you don't need separete threads to implement this case, this is simple one thread task.
Upvotes: 0
Reputation: 950
Create Thread2 and start it at the end of invokedisplaymatrix.
I'm not sure why you're using threads if there isn't meant to be any concurrency going on, however.
Upvotes: 5
Reputation: 7192
You may want to take a look at the TPL. Tasks support your scenario out of the box(via the ContinueWith method).
I'm not sure why do you need 2 threads here though - threads are good to use when doing parallel work, which doesn't look like the case here.
Upvotes: 2