首页 / C# / 如何使函数阻塞直到它有数据要在C#中返回
如何使函数阻塞直到它有数据要在C#中返回
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何使函数阻塞直到它有数据要在C#中返回,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1637字,纯文字阅读大概需要3分钟。
内容图文
![如何使函数阻塞直到它有数据要在C#中返回](/upload/InfoBanner/zyjiaocheng/657/955ef2841bad4e1c9a3b1c948a3d4fc1.jpg)
如何制作一个自定义函数,该函数返回输出并阻塞直到输出可用?我在想类似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();
}
}
内容总结
以上是互联网集市为您收集整理的如何使函数阻塞直到它有数据要在C#中返回全部内容,希望文章能够帮你解决如何使函数阻塞直到它有数据要在C#中返回所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。