AutoResetEvent triggers itself

171 views Asked by At

i've got a weird behavior of AutoResetEvent

there is the code in Utils class:

class Utils
{
    public static AutoResetEvent FileDownloaded = new AutoResetEvent(false);
    public static void DownloadFileAsync(string sourceUrl, string toPath)
    {
        var webClient = new WebClient();
        var url = new Uri(sourceUrl); 
        FileDownloaded.Reset();
        webClient.DownloadStringCompleted += (s, e) => 
        {
            Debug.WriteLine("DownloadStringAsinc completed");
            if(e.Error != null || string.IsNullOrEmpty( e.Result))
            {
                               //do retries
            }
            else
            {
                FileDownloaded.Set();
            }
        };
        webClient.DownloadStringAsync(url);
    }
}

and there is the code when it is listened to:

public DoSomeWork()
{
    Utils.DownloadFileAsync(iniUrl, localIni);
    if(Utils.FileDownloaded.WaitOne(2222))
    {
     //....
    }
    else
    //it goes here at initial run
}

it called like this:

BackgroundWorker bw = new BackgroundWorker();

bw.DoWork += (object o, DoWorkEventArgs args) =>
     {
            DoSomeWork();
     }   
bw.RunWorkerAsync();       

in this case, first time when WaitOne is called, it returns false right away (like it was timed out). second time is ok there is even no "DownloadStringAsinc completed" in debug output. when i was calling Utils.FileDownloaded.WaitOne(2222) from main thread (i know it isn't right, was just testing) it worked like it is supposed to. but when i moved block to thread, this behavior appeared. also, if i make Thread.Sleep(200) before the "if" statement in later block, everything works fine

must add: code from Utils class is not called simultaneously from different places.

i may consider like: "ok the problem is solved for this application". but it is not solved for my head. i must understand.

0

There are 0 answers