Reputation: 1277
I'm calling a thread from within a for loop that closes a document. The problem is, the loop continues and tries to open another document before the code in the thread finishes. How can I pause the loop and wait for the document close event. Thanks.
edit
here is my code...
public void OpenFile()
{
for (int i = 0; i < 3; i++)
{
if (i != 1)
{
try
{
uiApp.OpenAndActivateDocument(TargetPath(i));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
ThreadPool.QueueUserWorkItem(new WaitCallback(CloseDoc));
}
}
static void CloseDoc(object stateInfo)
{
try
{
SendKeys.SendWait("^{F4}");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I tried adding 'Thread.Sleep(3000)' after CloseDoc, that didn't work. It looks like 'waitone methods in manual/auto reset event classes' would be my best bet. @GAPS can you elaborate? Thank you!
Upvotes: 0
Views: 317
Reputation: 9230
If you have to wait for each thread finishes, you may call all code in one thread. If you want to avoid freezing the UI - create a method:
public void DoWork()
{
foreach(/* your code here*/)
{
// do work with documents
}
}
and run it in on non-ui thread.
Upvotes: 1
Reputation: 7193
Please elaborate your question...
for time being to answer your question I will suggest you to use waitone
methods in manual/auto reset event classes
. you can notify your waiting thread that your document is closed and then you can proceed.
Upvotes: 0
Reputation: 28970
try with this code
private object verrou = new object();
for(int i = 0; i < index; i++)
{
lock (verrou )
{
// Access thread-sensitive resources.
}
}
Upvotes: 0
Reputation: 337
Without seeing your code, I can't answer for your specific case, but look into the lock keyword and/or wait handles
See this link:
http://msdn.microsoft.com/en-us/library/ms173179.aspx
Upvotes: 0