如何制作一个自定义函数,该函数返回输出并阻塞直到输出可用?我在想类似Console.ReadLine()的东西.像这样:
var resp = Output(); //blocks until output is sent.
...
//returns a string once SendOutput is called and hands over the string.
public static string Output() { /* what goes here? */ }
//Is this function even needed? Can I just fire Output somehow?
private static string SendOutput(string msg) { /* what goes here? */ }
...
//Calls sendoutput with the string to send.
SendOutput(msg);
基本上,我正在制作一个被监听的监听器,直到它获取数据为止(就像调用console.readline一样),并且我需要内部代码来制作该监听器.
解决方法:
您想要的是在其他一些工作完成时发出阻塞方法调用的信号. ManualResetEvent是实现此行为的好方法.没有循环,并且一旦工作线程表明已完成,返回实际上是瞬时的.
class Program
{
static void Main(string[] args)
{
Blocker b = new Blocker();
Console.WriteLine(b.WaitForResult());
}
}
public class Blocker
{
private const int TIMEOUT_MILLISECONDS = 5000;
private ManualResetEvent manualResetEvent;
private string output;
public string WaitForResult()
{
// create an event which we can block on until signalled
manualResetEvent = new ManualResetEvent(false);
// start work in a new thread
Thread t = new Thread(DoWork);
t.Start();
// block until either the DoWork method signals it is completed, or we timeout (timeout is optional)
if (!manualResetEvent.WaitOne(TIMEOUT_MILLISECONDS))
throw new TimeoutException();
return output;
}
private void DoWork()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++)
{
sb.AppendFormat("{0}.", i);
}
output = sb.ToString();
// worker thread is done, we can let the WaitForResult method exit now
manualResetEvent.Set();
}
}