Tim*_*995 -2 .net c# multithreading asynchronous task
我目前在使用抛出异常的方法时遇到了一些问题,但我不确定原因.该异常使我的应用程序崩溃.
System.NullReferenceException: Object reference not set to an instance of an object.
at Myapp.AutoProcess.<ToRead>d__36.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__1(Object state)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Run Code Online (Sandbox Code Playgroud)
我在一个单独的线程上运行该方法
Thread listenerThread = new Thread(() => ToRead());
listenerThread.Start();
Run Code Online (Sandbox Code Playgroud)
抛出异常的方法如下所示:
private async void ToRead()
{
while (true)
{
if (this.toRead.Count != 0)
{
string protocol = this.toRead[0];
string[] temp = protocol.Split(',');
string message = temp[0];
string UserName = temp[1];
Process(message, UserName);
this.toRead.RemoveAt(0);
}
await Task.Delay(200);
}
}
Run Code Online (Sandbox Code Playgroud)
它接收来自List的传入消息,并过滤掉Username和Message以将其发送到Process方法.如果有人可以帮助我,我将不胜感激.
注意:异常发生在Windows R2 2008 Server上每天运行一次.因此,我无法在Visual Studio中进行调试
Ste*_*ary 11
您看到该异常会导致您的进程崩溃,因为您正在使用某种async void方法.
而不是使用线程,使用任务,如下:
private async Task ToReadAsync()
Task listenerTask = Task.Run(() => ToReadAsync());
Run Code Online (Sandbox Code Playgroud)
现在,您将能够很好地检索异常listenerTask.Exception.但它可能不会给你更多细节.
可能发生的是你的toRead变量设置null在某个时刻.当前代码的整个概念是错误的; 像这样的轮询绝对不是将数据从一个线程发送到另一个线程的方式.检查BlockingCollection或类似的东西,以获得正确的方法.
| 归档时间: |
|
| 查看次数: |
7557 次 |
| 最近记录: |