what I am getting at is something like OpenFileDialog.Show() method that returns after indefinite amount of time, only after user does something (presses Ok in this case). Well, I know that I can achieve similar things for dialog controls by subclassing from dialog, or form, or something like that. But what if I want to do it for something totally unrelated to dialogs, e.g. I want to write a method InputStringToTextbox() that will return only after the user has entered a legal string into a textbox on the form and pressed Enter.
我得到的是类似OpenFileDialog.Show()方法的东西,它在无限期的时间后返回,只有在用户做某事之后(在这种情况下按Ok)。好吧,我知道我可以通过从对话框,表单或类似的东西进行子类化来实现对话框控件的类似功能。但是,如果我想做一些与对话完全无关的事情,例如我想编写一个方法InputStringToTextbox(),只有在用户在表单上的文本框中输入合法字符串并按Enter键后才会返回该方法。
I do have some basic exposure to the concepts of threads and C#'s BeginInvoke/EndInvoke stuff, but I don't quite understand how to apply these ideas to this specific situation.
我确实有一些基本的线程概念和C#的BeginInvoke / EndInvoke的东西,但我不太明白如何将这些想法应用于这种特定的情况。
If you need to block threads, refer to the ManualResetEvent and AutoResetEvent classes. These are basic synchronization types that don't come with the extra baggage of types like Monitor, and in fact, many of the .NET synchronization types are built on top of them.
如果需要阻塞线程,请参阅ManualResetEvent和AutoResetEvent类。这些是基本的同步类型,没有像Monitor这样的类型的额外包袱,事实上,许多.NET同步类型都建立在它们之上。
Here is a short example demonstrating the use, for the context you provided.
以下是一个简短的示例,演示了您提供的上下文的用法。
static class ThreadEntryPoints
{
public static Main()
{
ShowDialog();
}
public static Other_Main()
{
// ... do some work ...
_event.Set();
}
private static ShowDialog()
{
// ... do some work ...
_event.WaitOne(/* optionally set timeout */);
}
private static readonly ManualResetEvent _event = new ManualResetEvent(false);
}
You can just implement a method that waits for something to happen.
您可以实现一个等待某事发生的方法。
void MainMethod()
{
...
...
DoSomethingAndWait()
...
}
private void DoSomethingAndWait()
{
...
...
while(!somethingHappened) //updated by other thread
{
Thread.Sleep(100) ;
}
...
}
The method you reference works because it calls a .NET API that doesn't return until the user event happens. You can do something similar.
您引用的方法之所以有效,是因为它调用的.NET API在用户事件发生之前不会返回。你可以做类似的事情。
Assuming WinForms:
If you want to make sure that the UI doesn't hang, you need to make sure to call Application.DoEvents() in your wait loop. If you don't do that, the UI will freeze.
如果要确保UI不挂起,则需要确保在等待循环中调用Application.DoEvents()。如果您不这样做,UI将冻结。
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2009/07/02/c156be4d95e13af52c166dbd298b8ceb.html。