1
A類包含變量A以保存在C類(doEvent())中觸發的事件的狀態。該線程休眠500毫秒,因爲它等待B類啓動事件,該事件將EventArg數據發送回C類並調用事件處理程序UpdateClassVar(EventArgs e) - 這就是它所等待的事件。C#.net事件處理程序代理問題
問題:如何使用Event Handler觸發依賴於狀態更新而不依賴於Thread.Sleep的類C(//執行某些操作)的下一步...?
免責聲明:考慮我是一個新手程序員。考慮這個我最好的嘗試和一個相當不雅的解決方案。請隨時重新設計和重新編碼,這應該被認爲是解決上述問題的唯一原型努力。
注意:代碼示例編輯爲實際應用的「真實世界」示例。 (未完全測試)
附加問題 - Thread.Sleep(400)在下面的示例中停止主線程...停止所有進程,儘管尋找替代方案,這是否甚至是一個可行的解決方案?
public class OrderA : ICurrencyOrder
{
private int _clid;
private string _status;
public int Clid
{
get { return _clid; }
set { _clid = value; }
}
public string Status
{
get { return _status; }
set { _status = value; }
}
}
Class B
{
// event delegate for UpdateOrder
public event UpdateOrderDelegate UpdateOrderEvent;
/* Code Here to receive and process order assign status etc */
/* An Event Arguments (args) Class is created that hold e.Status and e.Clid values */
UpdateOrder(args)
private void UpdateOrder(args)
{
if (UpdateOrderEvent != null)
{
UpdateOrderEvent(this, e);
}
}
}
// This is the class that initates the order (sendOrder()) and then waits for the
// status of the order before processing the next step in the order process
// which could be to send order again to exit
Class C
{
// add event handler to update status and clid from Class B
UpdateOrderEvent += new UpdateOrderDelegate(UpdateOrdersListener);
public void EnterOrder(EnterEventArgs e)
{
// set connectinon to ICurrencyOrder class above OrderA
// this uses a switch statement (omitted) to use correct class (A, B, C etc).
ICurrencyOrder ordVals = Class A;
bool fill = false;
for (int i=0; i<5 && fill=false; i++)
{
sendOrder("Symbol", price, clid, etc)
Thread.Sleep(400);
if (ordVals.Clid = clid) // check to see if order was updated using client id
{
if (ordVals.Status = 'FILLED')
{
filled = true;
}
}
} // end for loop
} // end EnterOrder
private void UpdateOrdersListener(object sender, EventArgs e)
{
OrderUpdateEventArgs ev = (OrderUpdatEventArgs)e;
// set connection to appropriate class using switch (symbol) omitted
ICurrencyOrder ordVal = Class A;
ordVal.Status = e.Status;
ordVal.Clid = e.Clid;
} // end Class C