我有一个类的以下骨架。正如您在 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
}
最佳答案
事件是由引发该事件的同一个线程
创建的。这个原理听起来很简单,但了解起来很重要。
所以:
场景 1 应用程序已打开。 Webtext
由 UI 线程中的表单初始化,并调用其发送。 Webtext
同步发送请求并触发事件。整个过程中,所有操作都是在UI线程上完成的。
场景 2 应用程序已打开。 Webtext
由 UI 线程中的表单初始化,并调用其发送。 Webtext
使用工作线程异步发送请求。第二个线程在完成时触发该事件。这将是工作线程(后台或前台取决于您创建线程的方式)。通过此线程对 UI 元素的任何调用都需要使用 Invoke
来完成。
如您所见,这很大程度上取决于您如何实现发送方法。我看不到发送本身的任何实现,所以我只能说您是否生成线程或使用线程池它将在工作线程上,否则简单地同步发送将在 UI 线程上。
关于c# - 如果异步引发,事件会起作用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4235639/