我正在使用UDP侦听器Windows应用程序,一旦UDP消息到达应用程序,我就会创建一个新的专用线程,该线程执行与此udp消息相关的例程。
这个例程被称为异步。
为何选择asynch?
主要是为了保持UDP的顺序,因为异步调用在线程池中排队(如果让每个线程运行同步,则不是这种情况)。
我的问题:
我希望我能够很好地实现我想要实现的目标
为我糟糕的英语道歉
此致
xPridex
N.B:这不是准确的代码我删除了很多关于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);
}
答案 0 :(得分:1)
该代码没有明显的错误,但我确实有一些意见:
new Thread
不使用线程池,它总是创建一个新的专用线程。如果您必须按接收顺序处理消息,则不应在单独的线程中处理每条消息。而是将每条消息添加到队列中,并在后台线程中按顺序处理队列中的每个项目。
线程没有任何内置的方式来警告创建者完成或返回结果。如果您想这样做,请使用System.MulticastDelegate.BeginInvoke
;使用线程池。如果您想在线程运行时获得中间结果,请使用BackgroundWorker
。