0

我想等待 GetValues.Get 方法并将值同步返回给调用者。ServerDataProvider、BookDataFetcher 类在 mycode 外部,我无法控制。非常感谢任何有关如何实现这一目标的帮助。

namespace Test {
class Program
{
    static void Main(string[] args)
    {
        GetValues val = new GetValues();
        val.Get("BOOKS", DataHandler);
        Console.ReadKey();
    }

    static void DataHandler(IList<string> values) {
    }
}

class GetValues
{
    public delegate void DataHandler(IList<string> values);
    public event DataHandler OnReceiveDataHandler;

    public void Get(string colName, DataHandler handler)
    {
        OnReceiveDataHandler += handler;
        GetDataFromServer svr = new GetDataFromServer();
        svr.OnReceiveDataHandler += OnReceiveData;
        svr.GetData(colName);
    }

    // Callback Handler
    private void OnReceiveData(IList<string> values) {
        OnReceiveDataHandler(values);
    }
}

class GetDataFromServer
{
    internal delegate void DataHandler(IList<string> values);
    internal event DataHandler OnReceiveDataHandler;

    internal void GetData(string columnName)
    {
        ServerDataProvider datafetcher = new ServerDataProvider();
        datafetcher.OnReceiveDataHandler += OnReceiveData;
        Task.Factory.StartNew(() => datafetcher.GetDataFromServer(columnName));
    }

    // Callback Handler
    private void OnReceiveData(IList <string> values) {
        OnReceiveDataHandler(values);
    }
}

class ServerDataProvider
{
    internal delegate void DataHandler(IList<string> values);
    internal event DataHandler OnReceiveDataHandler;

    public void GetDataFromServer(string columnName)
    {
        BookDataFetcher b = new BookDataFetcher();
        b.OnReceiveDataHandler += OnReceiveData;
        Task.Factory.StartNew(() => b.GetBookData(columnName));
    }

    // Calback Handler
    private void OnReceiveData(IList<string> values)
    {
        OnReceiveDataHandler(values);
    }
}

class BookDataFetcher
{
    internal delegate void DataHandler(IList<string> values);
    internal event DataHandler OnReceiveDataHandler;

    public void GetBookData(string col)
    {
        Thread.Sleep(5000);
        OnReceiveDataHandler(new List<string> {"Book1", "Book2"});
    }
}

}

4

1 回答 1

1

您所问的可以使用MethodImplAttribute来实现

 [MethodImplAttribute(MethodImplOptions.Synchronized)] 
 public void MethodA()
于 2013-07-31T17:27:44.207 回答