📜 ⬆️ ⬇️

Programming Threads under Compact Framework

Probably every person who programs under the .NET Framework or Compact Framework, at least once in his life faced with threads (Thread). And often there was a problem of starting a function with a call to a static method, in particular this concerns those methods where a change in the form controls occurs. In this article I will tell you how to solve this problem.

Consider the following example. There is some function foo ():
int a=0;
void Foo()
{
for ( int i=0;i<100000;i++)
{
a++;
}
MessageBox.Show(a.ToString());
}


* This source code was highlighted with Source Code Highlighter .

The easiest way to perform this function in a stream:
using System.Threading;

Thread thr= new Thread(Foo);
thr.Start();


* This source code was highlighted with Source Code Highlighter .

Now we change our function like this:
int a=0;
void Foo()
{
for ( int i=0;i<100000;i++)
{
a++;
label1.Text=a.ToString();
}
}

* This source code was highlighted with Source Code Highlighter .

As a result, an error will occur:
SmartDeviceProject1.exe
NotSupportedException
Control.Invoke must be used for a separate thread.
...
at System.Windows.Forms.Control.get_Text ()
at System.Windows.Forms.Control.set_Text (String value)
at SmartDeviceProject.Form1.Foo ()

This means that the interaction with the control should be in a separate thread.
Another way is to use the thread pool and the delegate:
ThreadPool.QueueUserWorkItem( delegate { Foo(); });

* This source code was highlighted with Source Code Highlighter .

Under Windows, everything is fine, but under Windows Mobile the same error pops up.
To solve this problem, you need to use the Invoke method for each control.
Create a Label1 text change function:
void ChangeLabel1Text( string text)
{
label1.Text = text;
}


* This source code was highlighted with Source Code Highlighter .

Add a delegate for this function:
delegate void ChangeLabel1TextDelegate( string text);
ChangeLabel1TextDelegate cltd;
cltd = new ChangeLabel1TextDelegate (ChangeLabel1Text);


* This source code was highlighted with Source Code Highlighter .

In the function Foo () we change the string
label1. Text = a.ToString ();

* This source code was highlighted with Source Code Highlighter .

on:
label1.Invoke(cltd, a.ToString());

* This source code was highlighted with Source Code Highlighter .

We start the flow for execution:
ThreadPool .QueueUserWorkItem( delegate { Foo(); });

* This source code was highlighted with Source Code Highlighter .


Everything. Now when you start the program on a PDA or smartphone, you will see numbers from 1 to 100,000.

Original: forum.wce.by/viewtopic.php?f=15&t=14221&start=0

')

Source: https://habr.com/ru/post/65111/


All Articles