I have a winform (MyFrm) which contains a winforms user control (myWinformUserControl). I call a public method (MyMethod) from this user control:
using (var frm = new MyFrm())
{
frm.myWinformUserControl.MyMethod();
}
public class myWinformUserControl: System.Windows.Forms.UserControl
{
public void MyMethod()
{
// Do some stuff
TryToDisconnect();
}
private void TryToDisconnect()
{
myComObj.Disconnect(); // This throws COMException
}
}
This user control communicates with a COM object. When I call to disconnect on the COM Object an exception is thrown:
COMException: Cannot call a 'Disconnect()' from within an event
so in order to solve this I use a thread instead of calling it directly:
public void MyMethod()
{
System.Threading.Thread th = new System.Threading.Thread(new
System.Threading.ThreadStart(TryToDisconnect));
th.SetApartmentState(System.Threading.ApartmentState.STA);
th.IsBackground = true;
th.Priority = System.Threading.ThreadPriority.Highest;
th.Start();
}
The below block of code indicated at the beginning of this question:
using (var frm = new MyFrm())
{
frm.myWinformUserControl.MyMethod();
}
... is called from a WPF MVVM view model class.
The problem I have here is that I need MyMethod to be done immediatelly so I set highest priority for the thread, and I want the call in view model class (frm.myWinformUserControl.MyMethod()) to stop and do not continue until this thread is completed. I have observed that the thread is not immediatelly executed, so how can I achieve this?
I have tried an asynchronous call and wait until it is completed instead of using a thread:
public void MyMethod()
{
Action action = Foo;
IAsyncResult result = action.BeginInvoke(ar => action.EndInvoke(ar), null);
result.AsyncWaitHandle.WaitOne();
}
public delegate void Action();
private void Foo()
{
TryToDisconnect();
}
but again the same COMException is thrown:
COMException: Cannot call a 'Disconnect()' from within an event
Also, in case of using the thread, If I immediatelly do th.Join() just after doing th.start() it does not work.