DragDrop.DoDragDrop不执行拖放操作时返回到Excel中

我的应用程序有一个简单的function,它连接到Excel,并将做拖放操作之间。 具体来说,我只是从我的应用程序中获取一些文本值,将它们拖放到Excel中,然后将其删除。

这是90%的时间,但奇怪的是,在某些时候,我的应用程序只是冻结。 我附加debugging器,并暂停执行,它被困在DragDrop.DoDragDrop – 这个函数永远不会返回,我的应用程序将永远挂起。

有没有办法确保DoDragDrop可以返回? 或者某种超时? 这种情况只会在我把数据放入Excel的时候才会发生,所以就我所知,放置正在完成,函数应该在我的应用程序中返回。

这是我使用的代码:

 DragDrop.DoDragDrop(sender as DependencyObject, draggable.GetDragDropString(), DragDropEffects.Copy); 

GetDragDropString()只是一个函数,它返回的数据string放在Excel中。 sender只是我拖动的UI组件。 像网格,编辑框,文本框等可以是其中的任何一个。

谢谢你的帮助!

编辑:由于DragDrop.DoDragDrop在某些情况下返回的问题,也许有人可以帮助编写一个适当的超时? 我试着开始一个新的Thread ,让它超时,这在简单的情况下工作,当线程内的工作不需要UI资源。 然而,当我用一个超时的新线程调用DoDragDrop时,它会抛出一个exception,说明线程不能访问该对象,因为不同的线程拥有它。 所以我需要在同一个线程中调用这个函数。 所以基本上我需要在UI线程超时,当这个函数在一定的时间内没有返回。

我想下面应该做这个工作,但是随着我走,我会分解它

 public class DragDropTimer { private delegate void DoDragDropDelegate(); private System.Timers.Timer dragTimer; private readonly int interval = 3000; public DragDropTimer() { dragTimer = new System.Timers.Timer(); dragTimer.Interval = interval; dragTimer.Elapsed += new ElapsedEventHandler(DragDropTimerElapsed); dragTimer.Enabled = false; dragTimer.AutoReset = false; } void DragDropTimerElapsed(object sender, ElapsedEventArgs e) { Initiate(); } public void Initiate() { // Stops UI from freezing, call action async. DoDragDropDelegate doDragDrop = new DoDragDropDelegate(DragDropAction); // No async callback or object required doDragDrop.BeginInvoke(null, null); } private void DragDropAction() { dragTimer.Enabled = false; // Do your work here. or do work before and disable your timer upto you. } } 

所以我们有一个基本类DragDropTimer 。 我们在构造函数中设置了我们想要的时间间隔,如果您愿意,我们可以调用DragDropTimerElapsed on计时器。

Initiate是你需要启动拖动function,它创build一个简单的委托,我们要求它执行的DragAction步骤,这是你做你的工作和定时器被禁用的地方。 只有在DragDrop成功的情况下,才可以select禁用定时器。 如果计时器过去了,我们再次调用Initiate重新开始。

另一个select是以下面的方式在一个单独的线程中执行drop

 Task.Factory.StartNew( () => { ... } );