开发者

Creating Threads in C#

开发者 https://www.devze.com 2023-01-10 20:41 出处:网络
I am trying to get a thread working in C# to reset the time and run another function alongside it. The code I have is:

I am trying to get a thread working in C# to reset the time and run another function alongside it. The code I have is:

Thread loopTime = new Thread(this.someFunction);
loopTime.Start();

for (int i = 0; i < 20; i++)
{
    ChangeTimeFunction(someTime);
    Thread.Sleep(200);
开发者_Go百科}

I am getting a threading error if I pass in this.SomeFunction(). This cannot be used according to Visual Studio. I could have the for loop as a thread but I do not know how to pass in the variable someTime.

Is there a way to either pass the variable into the loop if it was a function or call the for loop from within the function.

Thanks for any help.

UPDATE:

someFunction is a recorded methods using Visual Studio. This cannot be used outside the main thread. I would need to put the for loop inside the thread I am creating. Does any one know how to do this?

Thanks


Is there a way to either pass the variable into the loop if it was a function or call the for loop from within the function.

.NET has two delegates for starting threads. The first is ThreadStart, which just calls a method with no arguments.

The second is ParameterizedThreadStart, which calls a method with a single object as a parameter.

C# will implicitly create a ParameterizedThreadStart delegate if you pass a method in the Thread constructor that has an object argument. You then send an object to it using the thread's .Start(Object) method.

For example, to make the for loop a thread, assuming someTime is a DateTime and including a cast to that effect:

Thread loopTime = new Thread(someFunction);
loopTime.Start(someTime);

public void someFunction(object someTime) {
    for (int i = 0; i < 20; i++)
    {
        // Note the cast here... I assumed it's a DateTime
        ChangeTimeFunction((DateTime) someTime);
        Thread.Sleep(200);
    }
}


I think this link: http://msdn.microsoft.com/en-us/library/aa645740%28VS.71%29.aspx can explain what you need to do. It seems the ThreadStart delaget will allow you to pass it a function to execute when the thread is started.


It does not sound like problem of "this" qualifier.

Does your someFunction accept a parameter? If yes you can either:

  1. Make it parameterless and pass data thru member field
  2. Use can use closure to pass variable from the outer scope.

    int i = 2;
    Thread t = new Thread(x =>
                              {
                                  i++;                                      
                              });
    
    t.Start();
    
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号