我有以下類的骨架。正如你可以在TODO中看到的:評論我將在這裏實現一個AsyncEnumerator結構。此方法將抓取請求並將數據傳遞給另一個要處理的方法。基於這個過程,我想調用事件,SendMilestoneReached或SendFailed。我擔心這些可能發生在AsyncEnumerator的另一個線程上。如果異步引發,事件是否正常工作?
這是否會影響將調用Webtext類的UI線程?
/// <summary>
/// Sends Webtexts.
/// </summary>
public class Webtext
{
#region Event Definitions
// Events.
public event EventHandler<SendingEventArgs> SendStarted = delegate { };
public event EventHandler<SendingEventArgs> SendFailed = delegate { };
public event EventHandler<SendingEventArgs> SendSuccessful = delegate { };
public event EventHandler<SendingEventArgs> SendMilestoneReached = delegate { };
// Shared EventArgs Object, Consumed by the Events.
SendingEventArgs EventArgs = new SendingEventArgs();
#endregion
/// <summary>
/// Executes the send request.
/// </summary>
/// <param name="Operator">The operator whos service to use.</param>
/// <param name="Username">The username of the requested operator.</param>
/// <param name="Password">The password of the requested operator.</param>
/// <param name="Content">The content to send.</param>
/// <param name="Recipient">The recipient to recieve the content.</param>
public void ExecuteSendRequest(string Operator,
string Username,
string Password,
string Content,
string Recipient)
{
//TODO: Implement Async requests here.
}
#region Event Handlers
/// <summary>
/// Called when [sending started].
/// </summary>
protected void OnSendingStarted()
{
SendStarted(this, EventArgs);
}
/// <summary>
/// Called when [send fail].
/// </summary>
protected void OnSendFail()
{
SendFailed(this, EventArgs);
}
/// <summary>
/// Called when [send successful].
/// </summary>
protected void OnSendSuccessful()
{
SendSuccessful(this, EventArgs);
}
/// <summary>
/// Called when [send milestone reached].
/// </summary>
protected void OnSendMilestoneReached()
{
SendMilestoneReached(this, EventArgs);
}
#endregion
}
雖然我沒有包含實現,但我認爲你的第二個場景是適用的。基本上我將使用一個webrequest對象並異步調用它。它由第三方庫處理,允許我按順序編寫調用,但它仍然在另一個線程上觸發。你有關於如何使用調用將事件激發回UI線程的鏈接。 – deanvmc 2010-11-21 00:07:30
你可以通過「調用UI線程C#」進行谷歌搜索。這一個是非常簡短的:http://blogs.msdn.com/b/csharpfaq/archive/2004/03/17/91685.aspx – Aliostad 2010-11-21 00:15:43
我在想這個:http://stackoverflow.com/questions/1698889/raise-events-in-net-on-the-main-ui-thread,因爲它看起來更有活力。 – deanvmc 2010-11-21 00:18:07