使用C#进行多线程和协调(Multithreading and concurency with C#)

编程入门 行业动态 更新时间:2024-10-26 08:20:36
使用C#进行多线程和协调(Multithreading and concurency with C#)

在Windows窗体窗口中,多个事件可以触发异步方法。 该方法下载一个文件并对其进行缓存。 我的问题是我想让该方法执行一次。 换句话说,我想阻止文件被多次下载。

如果下载文件的方法被触发两次,我希望第二次调用等待文件(或等待第一个方法完成)。

有人对如何实现这一目标有想法吗?

更新 :我只是试图防止不必要的下载。 在我的情况下,当客户将鼠标放在ListBox中的某个项目上超过几毫秒时,我们开始下载。 我们假设用户将点击并请求文件。 可能发生的事情是,用户将鼠标悬停在项目上一秒钟,然后单击。 在这种情况下,两个下载开始。 我正在寻找处理这种情况的最佳方式。

更新2:有可能用户将鼠标移动到多个项目上。 结果是,会发生多次下载。 在这种情况下,我并没有很强硬,但现在如果我们面对这种情况,我们不会放弃下载。 该文件将被下载(文件通常在50-100kb左右),然后将被缓存。

In a Windows Form window, multiple events can trigger an asynchronous method. This method downloads a file and caches it. My problem is that I want that method to be executed once. In other words, I want to prevent the file to be downloaded multiple times.

If the method downloading the file is triggered twice, I want the second call to wait for the file (or wait for the first method to be done).

Does someone have an idea on how to achieve that?

UPDATE: I am simply trying to prevent unnecessary downloads. In my case, when a client put its mouse over an item in a ListBox for more than a couple milliseconds, we start to download. We make the assumption that the user will click and request the file. What can potentially happen is that the user keeps his mouse over the item for one second and then click. In this case two downloads start. I am looking for the best way to handle such scenario.

UPDATE 2:: There is a possibility that the user will move its mouse over multiple items. In consequences, multiple downloads will occur. I've not really tough of this scenario, but right now if we face such scenario we don't abandon the download. The file will be downloaded (files are usually around 50-100kb) and then are going to be cached.

最满意答案

保持表单变量的状态,并让异步方法在执行任何操作之前检查该状态。 不过,请确保您同步访问权限! 互斥和信号量对于这种事情是很好的。

如果您可以同时下载不同的文件,则需要跟踪列表中下载的内容以供参考。

如果一次只能下载一个文件,并且您不想排队等待,则可以在正在下载某些内容时解除该事件,并在下载完成时重新挂钩。

Maintain the state of what's happening in a form variable and have your async method check that state before it does anything. Make sure you synchronize access to it, though! Mutexes and semaphores are good for this kind of thing.

If you can download different files simultaneously, you'll need to keep track of what's being downloaded in a list for reference.

If only one file can be downloaded at a time, and you don't want to queue things up, you could just unhook the event while something is being downloaded, too, and rehook it when the download is complete.

更多推荐

本文发布于:2023-08-04 05:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1409436.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多线程   和协调   concurency   Multithreading

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!