0

I have a ThreadStatic variable declared in my main form as such:

[ThreadStatic]
public bool _skipCurrent = false;

I have execute another function and feed data back to my main form using the following code:

var updateMe = new Progress<RunProgressModel>(progress =>
{
    // This works
    lblTest.Text = progress.Message;
});

await Task.Run(() => monitor.Start(updateMe));

"monitor.Start" is in another class within another project and looks like this:

public void Start(IProgress<RunProgressModel> progress)
{
    var currentIndex = 0;
    var updateData = new RunProgressModel();

    foreach (var task in tasks)
    {
         bool done = false;

        while (!done)
        {
            // Perform tasks
            updateData.Message = "I did a thing.";
        }

        progress.Report(updateData);
    }
}

I need to access the _skipCurrent from inside that thread, to see if the task needs to finish processing that task earlier than it normally would, how do I get this Start function to see the ThreadStatic variable?

I essentially want the user to be able to click a "Skip" button that would set _skipCurrent to true, the thread to skip its current task, and then set the variable back to false.

MrDKOz
  • 207
  • 2
  • 11

1 Answers1

2

The ThreadStatic variable is a static variable that you can access just like any static variable, i.e. MainForm._skipCurrent. However, the ThreadStatic variable will not achieve what you want. Each thread has its own copy of a ThreadStatic variable to work with. So, if the user clicks a Cancel button in the UI thread and this sets MainForm._skipCurrent to true, the thread executing Start() will not see that value.

What you want is to use an ordinary static variable.

RobertBaron
  • 2,817
  • 1
  • 12
  • 19