I want to know how to use Asynchronous Processing SemaphoreSlim.Wait().I want to know why Task.Run is not running.

Asked 2 years ago, Updated 2 years ago, 277 views

As for the code in the comment section of the convert function of the presentation code, the asynchronous processing using semaphore does not proceed.Why is this?
I think it's probably how to use semaphore.Wait(); but as per the reference below

Block the current thread until it is in SemaphoreSlim.`

So in this case, isn't it a stopper to prevent more than three threads from standing up?What do you think?I don't know why, but I would like to know why Task.Run() is not running.

Reference site: https://learn.microsoft.com/ja-jp/dotnet/api/system.threading.semaphoreslim.wait?view=net-6.0

'HEIC_SimpleConverter.exe' (CoreCLR:clrhost): 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.10\System.ObjectModel.dll' loaded.Failed to read symbol.The module is optimized and the debug option My Code Only setting is enabled.
'HEIC_SimpleConverter.exe' (CoreCLR:clrhost): 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.10\System.Private.Uri.dll' loaded.Failed to read symbol.The module is optimized and the debug option My Code Only setting is enabled.
aaaaaa5
'HEIC_SimpleConverter.exe' (CoreCLR:clrhost): 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.10\System.ComponentModel.dll' loaded.Failed to read symbol.The module is optimized and the debug option My Code Only setting is enabled.
Thread 0x4710 ended with code 0(0x0).
Thread 0x2934 ended with code 0(0x0).
Thread 0x622c ended with code 0(0x0).

using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Threading;
using System.Windows.Forms;
using ImageMagic;

namespace HEIC_SimpleConverter
{
    public partial class Form: System.Windows.Forms.Form
    {
        public Form()
        {
            InitializeComponent();
           
        }

        string saveFolder;
        SemaphoreSlim semaphore=new SemaphoreSlim(0,3);
        List<string>file=new List<string>();;
        float per = 0;
        US>//#string folderPath=";
        List<Task>task=new List<Task>();

        /*##########################################################################
        # When D&D is done
        ############################################################################*/
        private void Form_DragDrop(object sender, DragEventArgse)
        {
            string[]str=(string[])e.Data.GetData(DataFormats.FileDrop, false);
            // Debug.WriteLine(str[0]);

            for (inti=0;i<str.Length;i++)
            {
                file.Add(str[i]);
                listBox.Items.Add (Path.GetFileName(str[i]));
            }
        }


        /*##########################################################################
        # When the file is in the window,
        ############################################################################*/
        private void Form_DragEnter (object sender, DragEventArgse)
        {
            if(e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[]str=(string[])e.Data.GetData(DataFormats.FileDrop, false);

                pool flag = false;
                for (inti=0;i<str.Length;i++)
                {
                    string ext = Path.GetExtension(str[i]);
                    if((ext!=".HEIC")&(ext!="HEIF"))
                    {
                        flag = true;
                        break;
                    }
                }

                if(flag==true)
                {
                    e.Effect=DragDropEffects.None;
                }
                else
                {
                    e.Effect=DragDropEffects.All;
                }
            }
            else
            {
                e.Effect=DragDropEffects.None;
            }

        }

        /*##########################################################################
        # conversion button click
        ############################################################################*/
        private void button_Click (object sender, EventArgse)
        {
            folderBrowserDialog.ShowDialog(); // Save Location View
            folderPath=folderBrowserDialog.SelectedPath;//Contains storage location

            Convert(); // Save Directory Specification
        }


        /*##########################################################################
        # conversion
        ############################################################################*/
        private async void Convert()
        {
            progressBar.Value = 0;
            per = 100.0f/(float) file.Count();


            Debug.WriteLine("aaaaa" + file.Count);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            for (inti=0;i<file.Count;i++)
            {
                task.Add(Task.Run()=>
                {
                    semaphore.Wait();
                    Debug.WriteLine("file.Count" + file.Count);

                    Debug.WriteLine(file[4]);

                    /*
                    US>//#string filePath=folderPath+"/"+Path.GetFileName(file[i].ToString())+".jpeg";
                    string f = Path.ChangeExtension(file[i].ToString(), "jpeg");
                    ImageMagic.MagicImageimg = new ImageMagic.MagicImage(file[i].ToString());
                    img.Write(filePath);
                    img.Dispose();


                    This.Invoke(()=>{progressBar.Value+=(int)per;});
                    */

                    semaphore.Release();
                }));
            }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            button.Enabled = false;
            wait Task.WhenAll(task.ToArray());
            semaphore.Dispose();

            button.Enabled = true;

            // Reset
            progressBar.Value = 0;
            file.Clear();
            listBox.Items.Clear();
        }

        






        private void Form_Load (object sender, EventArgse)
        {

        }

        

    }
}

c# net winforms net-core

2022-11-06 13:30

1 Answers

SemaphoreSlim constructor is

public SemaphoreSlim(int initialCount, int maxCount);

It is shown thatSample and question codes are

SemaphoreSlim semaphore=new SemaphoreSlim(0,3);

Therefore, the initial value is 0 and the maximum value is 3.

On the other hand, the SemaphoreSlim.Wait method is

If a thread or task can enter a semaphore, decrement the properties by CurrentCount1.

and so on.
Since the initial value is 0, SemaphoreSlim.Wait() must be allowed in SemaphoreSlim.Release() before it can pass through.In fact, the referenced code is

//Restore the semaphore count to its maximum value.
Console.Write("Main thread calls Release (3) -->");
semaphore.Release (3);
Console.WriteLine("{0}tasks can enter the semaphore.",
                  semaphore.CurrentCount);
// Main thread waits for the tasks to complete.
Task.WaitAll(tasks);

It is shown thatThis is the first time SemaphoreSlim.Wait() can pass through.However, this part of the question code has been omitted.


2022-11-06 17:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.