如何在输出可用之前创建一个返回输出和块的自定义函数?我在想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
一样),我需要内部代码来制作阻塞程序。
答案 0 :(得分:4)
你想要的是阻塞方法调用在其他一些工作完成时发出信号。 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();
}
}
答案 1 :(得分:-1)
线程进程调用并使用后台工作程序在数据可用时通知回来。
private void Create_Thread()
{
//Parameterized function
Thread wt = new Thread(new ParameterizedThreadStart(this.DoWork));
wt.Start([/*Pass parameters here*/]);
}
public void DoWork(object data)
{
Thread.Sleep(1000);
//Process Data - Do Work Here
//Call Delegate Method to Process Result Data
Post_Result(lvitem);
}
private delegate void _Post_Result(object data);
private void Post_Result(object data)
{
//Process Result
}