开发者

ContextSwitchException problem in code

开发者 https://www.devze.com 2023-02-28 23:44 出处:网络
I have a windows svc, which makes a couple of wmi calls. This results in fairly long running code (a task which takes about two minutes), and is also freezing the UI thread (I intend to use background

I have a windows svc, which makes a couple of wmi calls. This results in fairly long running code (a task which takes about two minutes), and is also freezing the UI thread (I intend to use backgroundworker for the progressbar and another thread for the actual operation).

At the moment, prior to all of this, I get a contextswitchexception. The code itself works, as it executes successfully and does what's required if I paste it within the app itself.

At the moment, I have turned off the MDA for this exception and I am calling Application.DoEvents() just before th开发者_StackOverflowe long-running task. What else is required to get rid of this exception?

Thanks


You must be talking about the Managed Debugging Assistant that's called contextSwitchDeadlock instead. It is a direct consequence of your code freezing the UI thread. The warning is associated with COM, it uses the message loop of the UI thread to marshal calls for COM objects that are not thread-safe. If the UI thread isn't pumping the message loop then those calls cannot complete. WMI uses COM.

This is often a very real problem, deadlock in this scenario is pretty common. You could for example have the UI thread block on a worker thread completing a job. Looping on BackgroundWorker.IsBusy is a classic example. If that worker thread is making COM calls on an apartment-threaded COM object then deadlock is the outcome. The worker thread can't complete because the UI thread is blocking and not dispatching the COM call. The UI thread can't complete because the worker thread isn't making progress. Deadlock.

It sounds like it is not a real deadlock in your case. The time-out for the warning is one minute, iirc. If you don't mind the frozen UI then you don't otherwise have a real problem. Everything starts moving again after the UI thread continues its normal job. You won't score any points for elegance.

0

精彩评论

暂无评论...
验证码 换一张
取 消