Link to home
Start Free TrialLog in
Avatar of LeeHenry
LeeHenry

asked on

Thread Sleep

I would like to read all the images in one of my directories, and display each image to a user based on a given time interval. I wrote all the code, but my sleep thread is not working.. Can someone look over and see what I did wrong?

       destDir = Server.MapPath("./MyImages");
        DirectoryInfo di = Directory.CreateDirectory(destDir);
        images = Directory.GetFiles(destDir);
        imageArrLength = images.GetLength(0);
        for (i = 0; i < imageArrLength; i++)
        {
            temp = destDir + "\\";
            destDir = images[i].ToString();
            fileName = destDir.Replace(temp, "");
            destDir = "~/MyImages/" + fileName;
            _currentImage.ImageUrl = destDir;

           Thread.sleep(100);


        }
Avatar of dkloeck
dkloeck
Flag of Spain image

Yoe are setting it to sleep for 0,1 seconds, is that what you want?

HEre is an example on how to use Thread.sleep(Int32):

class ApartmentTest
{
    static void Main()
    {
        Thread newThread =
            new Thread(new ThreadStart(ThreadMethod));
        newThread.SetApartmentState(ApartmentState.MTA);

        // The following line is ignored since
        // ApartmentState can only be set once.
        newThread.SetApartmentState(ApartmentState.STA);

        Console.WriteLine("ThreadState: {0}, ApartmentState: {1}",
            newThread.ThreadState, newThread.ApartmentState);

        newThread.Start();

        // Wait for newThread to start and go to sleep.
        Thread.Sleep(300);
        try
        {
            // This causes an exception since newThread is sleeping.
            newThread.SetApartmentState(ApartmentState.STA);
        }
        catch(ThreadStateException stateException)
        {
            Console.WriteLine("\n{0} caught:\n" +
                "Thread is not in the Unstarted or Running state.",
                stateException.GetType().Name);
            Console.WriteLine("ThreadState: {0}, ApartmentState: {1}",
                newThread.ThreadState, newThread.GetApartmentState());
        }
    }

    static void ThreadMethod()
    {
        Thread.Sleep(1000);
    }
}

Avatar of CaldNT
CaldNT

Did you place that code in a thread?

You need to put the code you want to run in a method and run that method in a thread.

Here is a quick guide to threads:
http://www.csharphelp.com/archives2/archive409.html

Also what you are trying to do is not clear.
SOLUTION
Avatar of CaldNT
CaldNT

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of LeeHenry

ASKER

Thanks for all the comments.. I would like to use a javascript, but the problem is that the images are dynamically getting inserted into a directorty on my server. As far as I know, javascript can't access this directory. Therefore, i used c# to gain access to the directory, store the images in the array, and then display them via a slideshow. I see the problem though. All the code is executing on the server. I guess I was wrong with my approach to  using threads, for I thought that pause would allow the user to see each image before the next image was traversed in the array. Is there a way for me to create a slideshow via server side code?

You can build an array of the image paths and then use the javascript to cycle through them.

Would this work for you?
Update:

It works the way i would like if I create a refresh button, and loop through the images by clicking the refresh button. However, if I create a timer, and use the Exact same code as the refresh button, the images don't display? See my code below:

    private string destDir;
    private string[] images;
    private Thread[] timer;
    private int imageArrLength;
    private int i;
    private string fileName;
    private string temp;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            Session["counter"] = 0;

        for (int i = 0; i < 4; i++)
        {
            // create the timer set the event handler
            System.Timers.Timer t = new System.Timers.Timer();
            t.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
            t.Interval = 10000; //Set to 10 seconds.
            t.Enabled = true;
        }
    }

    protected void _refresh_Click(object sender, EventArgs e)
    {
        destDir = Server.MapPath("./MyImages");
        DirectoryInfo di = Directory.CreateDirectory(destDir);
        images = Directory.GetFiles(destDir);
        imageArrLength = images.GetLength(0);
        int counter = (Int32)Session["counter"];

        if (counter < imageArrLength)
        {
            temp = destDir + "\\";
            destDir = images[counter].ToString();
            fileName = destDir.Replace(temp, "");
            destDir = "~/MyImages/" + fileName;

            _currentImage.ImageUrl = destDir;
            destDir = Server.MapPath("./MyImages");
            images = Directory.GetFiles(destDir);
            imageArrLength = images.GetLength(0);
            counter++;
            Session["counter"] = counter;
        }
        else
        {
            counter = 0;
            Session["counter"] = counter;
            temp = destDir + "\\";
            destDir = images[counter].ToString();
            fileName = destDir.Replace(temp, "");
            destDir = "~/ MyImages/" + fileName;

            _currentImage.ImageUrl = destDir;
            destDir = Server.MapPath("./MyImages");
            images = Directory.GetFiles(destDir);
            imageArrLength = images.GetLength(0);
            counter++;
            Session["counter"] = counter;
        }
    }

    public void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        // Enter Code here to execute each time the timer has elapsed.  
        destDir = Server.MapPath("./MyImages");
        DirectoryInfo di = Directory.CreateDirectory(destDir);
        images = Directory.GetFiles(destDir);
        imageArrLength = images.GetLength(0);
        int counter = (Int32)Session["counter"];
        if (counter < imageArrLength)
        {
            temp = destDir + "\\";
            destDir = images[counter].ToString();
            fileName = destDir.Replace(temp, "");
            destDir = "~/MyImages/" + fileName;

            _currentImage.ImageUrl = destDir;
            destDir = Server.MapPath("./MyImages");
            images = Directory.GetFiles(destDir);
            imageArrLength = images.GetLength(0);
            counter++;
            Session["counter"] = counter;
        }
        else
        {
            counter = 0;
            Session["counter"] = counter;
            temp = destDir + "\\";
            destDir = images[counter].ToString();
            fileName = destDir.Replace(temp, "");
            destDir = "~/MyImages/" + fileName;

            _currentImage.ImageUrl = destDir;
            destDir = Server.MapPath("./MyImages");
            images = Directory.GetFiles(destDir);
            imageArrLength = images.GetLength(0);
            counter++;
            Session["counter"] = counter;
        }
    }
I think you could achieve what you want by creating a Web Service method which returns the image to be displayed, and using some AJAX on the webpage to call the web service and display this image.
You can do it a lot easier than that. On the server side get it to generate an array of URLs in javascript, then when the page loads on the client it can use that array of URLs to fetch the images from the server and change the image on the page.
I suggested that, but he mentioned that the available images on the directory are changing

"...but the problem is that the images are dynamically getting inserted into a directorty on my server."

By using a web service he can include logic to pay attention to images added to the directory.
Here is an example of a slideshow live on the internet, it is for a commerial component but the javascript is public to look at:
http://www.programmers.com.au/products/demo/slideshow.aspx
>> ...but the problem is that the images are dynamically getting inserted into a directorty on my server.

I understood this as they were changing dynamically meaning that the page couldn't hold the URLs to the images staticly. Just like a normal photo gallary on the internet people add images but they aren't adding them every second. Maybe I was wrong.
Thanks again for the comments.. How involved is  creating a Web Service method which returns the image to be displayed? How about generating an array of URLs in javascript? I'm open to all suggestions, it's just that I never did anything like that before, and I need to have this done pretty soon. Clicking the refresh button does accomplish what I would like, but the ideal solution would be to automatically accomplish this. I am still confused as to why it works when i click the refresh button, but not when I use a timer?

Creating the array is likely easier:
http://www.w3schools.com/js/js_obj_array.asp
>> I am still confused as to why it works when i click the refresh button, but not when I use a timer?
There is no WebControls.Timer that generates javascript. The timer you have made will fall out of scope before it executes because the request will be served. When you refresh you are calling the server asking it to complete another request.

You can generate javascript like the following in C#:

string[] imageUrls;
imageUrls[0] = "http://www.mysite.com/images/SomeImage.png";
imageUrls[1] = "http://www.mysite.com/images/AnotherImage.png";
imageUrls[2] = "http://www.mysite.com/images/AThirdImage.png";

Then use client side javascript to change an image. The link I posted above has the javascript to change images and wait between each one.
Oops, I just relised I typed C# for the javascript, take a look at the article on w3schools that CaldNTposted.
Problem... I looked at the link, and that would work perfect, if I knew what the image names would be, and how many I was working with. Since the images are dynamically getting created and deleted periodically, I have no way of knowing how to hard code those imag url's in my client side javascript. For that reason, i turned to C#. Perhaps Ajax can connect to  my directory? Either way, I think i understand now why my Timer and Thread were not working. Thanks for clearing that up for me. If you all think of another solution for this let me know.. Thanks
OK, if the images change a lot then you should probably use a Web Service method that returns the next image path, together with some Javascript that displays the image and requests another after the time interval.

If you need some help creating the Web Service or the required Javascript just tell me.