我正在开发一个 UDP 侦听器 Windows 应用程序,一旦 UDP 消息到达应用程序,我将创建一个新的专用线程,该线程执行与此 udp 消息相关的例程。
该例程被异步调用。
为什么异步?
主要是为了保持 UDP 即将到来的顺序,因为异步调用在线程池中排队(如果我让每个线程同步运行则不是这种情况)。
我的问题:
- 即使该例程在子线程中运行,异步运行例程也是一个好主意吗?
- 如果是的话,我是否应该为此异步调用实施 IsBusy 最佳实践,即使它是一种“一劳永逸”的模式?
我希望我能很好地解释我想要实现的目标
为我糟糕的英语道歉
问候
xPridex
注意:这不是准确的代码,我删除了很多关于 lisibity 的细节。
/// <summary>
/// Launch SendNotificationToEBSECW treatment.
/// </summary>
/// <param name="sender">object : UDPmsg_t_Mapping</param>
private void StartPrepared(object sender)
{
mainThread = new Thread(new ParameterizedThreadStart(EntryPointV3));
mainThread.Start(sender);
}
private readonly object _sync = new object();
private bool _myTaskIsRunning = false;
public bool IsBusy
{
get { return _myTaskIsRunning; }
}
public void DoWorkAsynch(Tuple.Create(x,y))
{
MyTaskWorkerDelegate worker = new MyTaskWorkerDelegate(EntryPointV3);
AsyncCallback completedCallback = new AsyncCallback(MyTaskCompletedCallback);
lock (_sync)
{
if (_myTaskIsRunning)
throw new InvalidOperationException("currently busy.");
AsyncOperation async = AsyncOperationManager.CreateOperation(null);
worker.BeginInvoke(Tuple.Create(x,y), completedCallback, async);
_myTaskIsRunning = true;
}
}
private void MyTaskCompletedCallback(IAsyncResult ar)
{
// get the original worker delegate and the AsyncOperation instance
MyTaskWorkerDelegate worker =
(MyTaskWorkerDelegate)((AsyncResult)ar).AsyncDelegate;
AsyncOperation async = (AsyncOperation)ar.AsyncState;
// finish the asynchronous operation
worker.EndInvoke(ar);
// clear the running task flag
lock (_sync)
{
_myTaskIsRunning = false;
}
// raise the completed event
AsyncCompletedEventArgs completedArgs = new AsyncCompletedEventArgs(null,
false, null);
async.PostOperationCompleted(
delegate(object e) { OnMyTaskCompleted((AsyncCompletedEventArgs)e); },
completedArgs);
}
public event AsyncCompletedEventHandler MyTaskCompleted;
protected virtual void OnMyTaskCompleted(AsyncCompletedEventArgs e)
{
if (MyTaskCompleted != null)
MyTaskCompleted(this, e);
}