c# - 强制主线程在 RunWorkerCompletedEventArgs 上使用 Return
问题描述
在我的应用程序中,我通过红外阅读器在设备中设置/获取数据。当我运行我的应用程序时,我有两种情况: - 设备一直在这里,我返回一个对象'RETOUR' - 设备一开始就在这里,但是当我的函数运行时有人断开了它。
在这两种情况下,我都想返回一个“RETOUR”类型的对象。
入口点必然是这样的函数:“public async Task XXX(dynamic input)”
我建立了一个后台工作人员,可以在设备断开连接时找到。它可以找到,但我不知道如何在调用 RunWorkerCompletedEventHandler 时强制我的异步任务返回一个对象。
在每个“异步任务”功能中启动后台工作程序的代码:
bw = new BackgroundWorker();
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(
delegate (object o, DoWorkEventArgs args)
{
// called when AwaitEpdRemoval have response
stack.EpdRemoved += (object sender, ConnectEventArgs e) =>
{
// Set the object i want to return
STATIC_FUNCTION.mon_retour.GestionErreur("154", null);
};
// While AwaitEpdRemoval don't throw EpdRemoved object
while (true && STATIC_FUNCTION.mon_retour.code_retour != "154")
{
try
{
if (bw.CancellationPending) {
args.Cancel = true;
break;
}
// If device still here
stack.AwaitEpdRemoval(discoveredEpd);
}
catch (Exception e)
{
// If the device is still the here the DLL throw error
System.Threading.Thread.Sleep(100);
}
}
});
// when the worker is completed
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
delegate (object o, RunWorkerCompletedEventArgs args)
{
// for now i close the app, but what i want is return STATIC_FUNCTION.mon_retour
System.Environment.Exit(1);
});
bw.RunWorkerAsync();
现在它关闭了一切,但我希望它停止其他代码并返回对象“STATIC_FUNCTION.mon_retour”
我该怎么做(即使我必须重写一切)。