我想等待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"});
}
}
}
答案 0 :(得分:1)
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public void MethodA()