3

如何制作一个返回输出并阻塞直到输出可用的自定义函数?我在想类似的东西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),并且我需要内部代码来制作阻塞器。

4

2 回答 2

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();
    }
}
于 2012-10-05T02:12:49.840 回答
-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
}
于 2012-10-05T01:51:03.627 回答