c# - 如何在c#中创建一个阻塞直到它有数据返回的函数 [英] How to make a function that blocks until it has data to return in c#
问题描述
如何创建一个返回输出并阻塞直到输出可用的自定义函数?我在想像 Console.ReadLine()
这样的东西.像这样:
How do I make a custom function that returns output and blocks until output is available? I'm thinking of something like Console.ReadLine()
. Something like this:
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
一样),我需要内部代码来制作阻止程序.
Basically I'm making a listener that is blocked until it gets data (like it would if calling console.readline
), and I need the internal code to make the blocker.
推荐答案
您想要的是在其他工作完成时通知您的阻塞方法调用.ManualResetEvent 是实现此行为的好方法;没有循环,一旦工作线程发出信号表示它已完成,返回几乎是即时的.
What you want is for your blocking method call to be signalled when some other work has completed. A ManualResetEvent is a good way to achieve this behaviour; there are no loops, and the return is virtually instantaneous once the worker thread signals that it is complete.
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();
}
}
这篇关于c# - 如何在c#中创建一个阻塞直到它有数据返回的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!