I have developed a simple Id checking windows forms with C# application to check a set of given Ids valid or not by passing to a webpage using webbrowser control and getting the reply and everything is working fine,its taking 40 - 60 seconds for 20 Ids.one by one.Now i want to speed up the same process using advance threading concept in C# .
Code is working fine i want to improve the performance using threading. any simple suggestion would be great help today
private void button2_Click(object sender, EventArgs e)
{
string url = "https://idscheckingsite.com";
WebBrowser wb = new WebBrowser();
wb.ScriptErrorsSuppressed = true;
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(Final_DocumentCompleted);
wb.Navigate(url);
}
private void Final_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wbs = sender as WebBrowser;
wbs.Document.GetElementById("pannumber").InnerText = ListsofIds[ids];
wbs.Document.GetElementById("frmType1").SetAttribute("value", "24Q");
HtmlElement btnlink = wbs.Document.GetElementById("clickGo1");
btnlink.InvokeMember("Click");
//string response = wbs.DocumentText;
wbs.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(Final_DocumentCompleted);
wbs.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(Final_result);
}
private void Final_result(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wbResult = sender as WebBrowser;
string status = wbResult.Document.GetElementById("status").InnerText;
string name = wbResult.Document.GetElementById("name").InnerText;
wbResult.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(Final_result);
wbResult.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(Final_DocumentCompleted);
DataRow dr = dt.NewRow();
dr[0] = PANNumber[ids];
dr[1] = status;
dr[2] = name;
dt.Rows.Add(dr);
++ids;
if (ids < 20)
wbResult.Navigate(vurl);
else
{
dataGridView1.DataSource = dt;
}
}
Working fine but need to improve the performance to the max using advance C# threading concepts if any .
Here is my suggestion. When the button2 is clicked, a number of worker tasks are started. A reasonable number is 4, but you can try different numbers until you get the best performance. Each worker task will use its own WebBrowser control, and will invoke a subset of the ids. For example the worker task #0 will invoke the ids 4, 8, 12, 16, and 20, the worker task #1 will invoke 1, 5, 9, 13, and 17 etc. Then all worker tasks will be waited to complete, and then the DataGridView can be updated. There is no multithreading involved. Everything happens in the UI thread. No locking or other thread synchronization is required.
private async void button2_Click(object sender, EventArgs e)
{
string url = "https://idscheckingsite.com";
const int WORKER_TASKS_COUNT = 4;
var workerTasks = new Task[WORKER_TASKS_COUNT];
for (int i = 0; i < WORKER_TASKS_COUNT; i++)
{
workerTasks[i] = DoWorkAsync(i);
}
await Task.WhenAll(workerTasks);
dataGridView1.DataSource = dt;
async Task DoWorkAsync(int workerIndex)
{
using (var wb = new WebBrowser())
{
wb.ScriptErrorsSuppressed = true;
for (int i = 0; i < ListsofIds.Length; i++)
{
if (i % WORKER_TASKS_COUNT != workerIndex) continue;
wb.Navigate(url);
await wb; // await for the next DocumentCompleted
wb.Document.GetElementById("pannumber").InnerText = ListsofIds[i];
wb.Document.GetElementById("frmType1").SetAttribute("value", "24Q");
HtmlElement btnlink = wb.Document.GetElementById("clickGo1");
btnlink.InvokeMember("Click");
await wb; // await for the next DocumentCompleted
string status = wb.Document.GetElementById("status").InnerText;
string name = wb.Document.GetElementById("name").InnerText;
DataRow dr = dt.NewRow();
dr[0] = PANNumber[i];
dr[1] = status;
dr[2] = name;
dt.Rows.Add(dr);
}
}
}
}
The code above uses an interesting technique to simplify the navigation of the WebBrowser control. Instead of subscribing and unsubscribing manually to the DocumentCompleted event, it is doing it automatically by awaiting the WebBrowser control. Normally this is not possible, but we can make it possible by creating an extension method that returns a TaskAwaiter:
public static class WebBrowserExtensions
{
public static TaskAwaiter<Uri> GetAwaiter(this WebBrowser wb)
{
var tcs = new TaskCompletionSource<Uri>();
WebBrowserDocumentCompletedEventHandler handler = null;
handler = (_, e) =>
{
wb.DocumentCompleted -= handler;
tcs.TrySetResult(e.Url);
};
wb.DocumentCompleted += handler;
return tcs.Task.GetAwaiter();
}
}
Update: After using my code myself I found await wb to be a bit confusing, because the WebBrowser control has many events that could be awaited. So I made it more explicit and extensible be creating an async version of the event (instead of an awaiter):
public static class WebBrowserExtensions
{
public static Task<Uri> DocumentCompletedAsync(this WebBrowser wb)
{
var tcs = new TaskCompletionSource<Uri>();
WebBrowserDocumentCompletedEventHandler handler = null;
handler = (_, e) =>
{
wb.DocumentCompleted -= handler;
tcs.TrySetResult(e.Url);
};
wb.DocumentCompleted += handler;
return tcs.Task;
}
}
It can be used like this:
await wb.DocumentCompletedAsync();
Then it becomes trivial to create more extension methods like NavigatedAsync or DocumentTitleChangedAsync for example.
Update: Waiting endlessly is not very nice, so a timeout (expressed in milliseconds) could be added as an argument in the awaited extension method. Since the whole code is intended to run exclusively in the UI thread I used a System.Windows.Forms.Timer, although a CancellationToken would be propably more convenient in general. The code is a bit involved to avoid memory leaks, that could be an issue for an application intended to run for many hours, and do thousands web requests.
public static class WebBrowserExtensions
{
public static Task<Uri> DocumentCompletedAsync(this WebBrowser wb, int timeout)
{
var tcs = new TaskCompletionSource<Uri>();
WebBrowserDocumentCompletedEventHandler handler = null;
var timeoutRegistration = WithTimeout(tcs, timeout,
() => wb.DocumentCompleted -= handler);
handler = (_, e) =>
{
wb.DocumentCompleted -= handler;
timeoutRegistration.Unregister();
tcs.TrySetResult(e.Url);
};
wb.DocumentCompleted += handler;
return tcs.Task;
}
public static Task<Uri> DocumentCompletedAsync(this WebBrowser wb)
{
return wb.DocumentCompletedAsync(30000); // Default timeout 30 sec
}
private static TimeoutRegistration WithTimeout<T>(
TaskCompletionSource<T> tcs, int timeout, Action eventRemove)
{
if (timeout == Timeout.Infinite) return default;
var timer = new System.Windows.Forms.Timer();
timer.Tick += (s, e) =>
{
timer.Enabled = false;
timer = null;
eventRemove();
eventRemove = null;
tcs.SetException(new TimeoutException());
tcs = null;
};
timer.Interval = timeout;
timer.Enabled = true;
return new TimeoutRegistration(() =>
{
if (timer == null) return;
timer.Enabled = false;
// Make everything null to avoid memory leaks
timer = null;
eventRemove = null;
tcs = null;
});
}
private struct TimeoutRegistration
{
private Action _unregister;
public TimeoutRegistration(Action unregister)
{
_unregister = unregister;
}
public void Unregister()
{
if (_unregister == null) return;
_unregister();
_unregister = null;
}
}
}
Update: As a side note, I see that you are suppressing script errors by using wb.ScriptErrorsSuppressed = true. Are you aware that you can configure the Internet Explorer version emulated by the WebBrowser control? To make the control emulate the latest (and final) version of Internet Explorer, the version 11, add this code at the start of your program:
Registry.SetValue(#"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION",
AppDomain.CurrentDomain.FriendlyName, 11000); // IE11
Related
Hi All: I want to run a function to check internet connection and update the UI content, so i'm using a Dispatchtimer in the WPF loaded, during the intenet check if the ping is blocked by the local server or for some x reasons the UI is blocking.
How can i call the function continuosly without blocking the UI & update the User interface? thanks.
private DispatcherTimer BackgroundAsyncTasksTimer;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
BackgroundAsyncTasksTimer = new DispatcherTimer();
BackgroundAsyncTasksTimer.Interval = TimeSpan.FromMilliseconds(2000);
BackgroundAsyncTasksTimer.Tick += BackgroundAsyncTasksTimer_Tick;
BackgroundAsyncTasksTimer.Start();
}
private async void BackgroundAsyncTasksTimer_Tick(object sender, object e)
{
if(CanConnectToTheInternet())
{
Dispatcher.Invoke((Action)delegate () {
einternetcoxn.Fill = (SolidColorBrush)new BrushConverter().ConvertFromString("#00ff00"); //Eclipse
checkNewversion();
bUpdatesoftware.IsEnabled = true;//button
});
}
else
{
Dispatcher.Invoke((Action)delegate () {
einternetcoxn.Fill = (SolidColorBrush)new BrushConverter().ConvertFromString("#841c34");
clearfields();
});
}
}
private static bool CanConnectToTheInternet()
{
try
{
string[] strArray = new string[5]
{
"8.8.8.8",
"https://www.google.com",
"https://www.microsoft.com",
"https://www.facebook.com",
};
if (((IEnumerable<string>)strArray).AsParallel<string>().Any<string>((Func<string, bool>)(url =>
{
try
{
Ping ping = new Ping();
byte[] buffer = new byte[32];
PingOptions options = new PingOptions();
if (ping.Send(url, 500, buffer, options).Status == IPStatus.Success)
return true;
}
catch
{
}
return false;
})))
return true;
if (((IEnumerable<string>)strArray).AsParallel<string>().Any<string>((Func<string, bool>)(url =>
{
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.KeepAlive = false;
httpWebRequest.Timeout = 5000;
using ((HttpWebResponse)httpWebRequest.GetResponse())
return true;
}
catch
{
}
return false;
})))
return true;
}
catch
{
return false;
}
return false;
}
A DispatcherTimeris not running the tick event on a background thread, at least not by default in a UI application.
But this should be fine if you change your CanConnectToTheInternetmethod to use Ping.SendAsync and WebRequest.GetResponseAsync. That will require you to follow the async await pattern, but this is an good example of the kind of task this pattern is meant for. In this case you should get rid of all the Dispatcher.Invoke-stuff, since all of your code would run on the UI thread.
The alternative would be to use a timer that runs the tick-event on a threadpool thread, like Timers.Timer. See also timer comparison
I would like to start a new thread in a for loop, then create a WebBrowser control in each thread, load a page, then do some HTML analysis. I tried to use the DocumentCompleted event, but it's never got hit. The threads seems starting properly, navigation too, but the event never fires. What's wrong with my baby?
public async void Roller2()
{
for (int i = 1; i <= 1000; i++)
{
Thread myThread = new Thread(() => this.Wrapper(i));
myThread.SetApartmentState(ApartmentState.STA);
myThread.Start();
await Task.Delay(1000);
}
}
public void Wrapper(int id)
{
ReadAsync(id);
}
public void ReadAsync(int ids)
{
WebBrowser website = new WebBrowser();
website.AllowNavigation = true;
website.ScriptErrorsSuppressed = true;
website.Navigate("http://www.someurl.com/id/" + ids.ToString());
website.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
}
void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//Do some analysis on sender as WebBrowser
}
I'm having some trouble accessing the UI from an another thread.
I understand the basics on cross-threading limitations, but I can't seem to write the code that will work. More specifically, I can't access the ListView from a static method (thread).
I'm trying to make it work with backgroundWorker.
Here's my code:
private void start_Click(object sender, EventArgs e)
{
ServicePointManager.DefaultConnectionLimit = 20;
var tasks = new List<Task<int>>();
foreach (ListViewItem item in listView1.Items)
{
string currentUrl = item.SubItems[1].Text;
int i = item.Index;
tasks.Add(Task.Factory.StartNew(() => { return GetWebResponse(currentUrl, i); }));
}
Task.WaitAll(tasks.ToArray());
}
private static int GetWebResponse(string url, int itemIndex)
{
int statusCode = 0;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
Task<HttpWebResponse> responseTask = Task.Factory.FromAsync<HttpWebResponse>(httpWebRequest.BeginGetResponse, asyncResult => (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult), null);
backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.WorkerSupportsCancellation = true;
backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
backgroundWorker.RunWorkerAsync();
return statusCode;
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
listView1.Items[0].ImageKey = "green";
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
while (!e.Cancel)
{
Thread.Sleep(5000);
backgroundWorker.ReportProgress(0);
}
}
This code doesn't work because backgroundWorker_DoWork and backgroundWorker_ProgressChanged are not static, but if I make them static then I can't access listView1
EDIT: Got it working. Code below for review
public delegate void delUpdateListView(int itemIndex, int statusCode);
public Form1()
{
InitializeComponent();
}
private void start_Click(object sender, EventArgs e)
{
ServicePointManager.DefaultConnectionLimit = 20;
var tasks = new List<Task<int>>();
foreach (ListViewItem item in listView1.Items)
{
string currentUrl = item.SubItems[1].Text;
int i = item.Index;
tasks.Add(Task.Factory.StartNew(() => {
//return GetWebResponse(currentUrl, i);
int statusCode = 0;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(currentUrl);
Task<HttpWebResponse> responseTask = Task.Factory.FromAsync<HttpWebResponse>(httpWebRequest.BeginGetResponse, asyncResult => (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult), null);
statusCode = (int)responseTask.Result.StatusCode;
object[] invParams = new object[2];
invParams[0] = i;
invParams[1] = statusCode;
if (InvokeRequired)
{
BeginInvoke(new delUpdateListView(UpdateListView), invParams);
}
else
{
Invoke(new delUpdateListView(UpdateListView), invParams);
}
return statusCode;
}));
}
Task.WaitAll(tasks.ToArray());
}
public void UpdateListView(int itemIndex, int statusCode) {
listView1.Items[itemIndex].ImageKey = "green";
}
I see several problems here:
1) I don't see why GetWebResponse needs to be static. The easiest solution would be to make it an instance method.
2) Why are you using the background worker anyway?
3) It doesn't make much sense to use Tasks and then wait for them to finish right after you spawn them. This blocks your application where it should be responsive.
As for 3): To keep the UI responsive and updatable, disable everything the user may not click before spawning the tasks, add a continuation action to each task that re-enables the UI components. The task may update the list using the usual Invoke calls.
So I can't say for sure this is the issue but I'm just about positive it is. I have a recordset of IVR calls to make. I put the data for each one in a concurrent queue and start 5 background workers to start working from the queue. However, after making 2 calls, the calls stop coming until one person hangs up, then it moves on to call number 3,4,5 etc. Are the any issues with this code?
It seems like the background workers are blocking eachother from calling the same method...? Is that possible?
private ConcurrentQueue<DataTable> _ivrCallsQueue = new ConcurrentQueue<DataTable>();
private List<BackgroundWorker> _ivrCallers = new List<BackgroundWorker>();
public overrid void Process()
{
foreach(DataRow row in _tblRecordsToProcess.Rows)
{
_workingActionItem = actionItemDAL.GetActionItemFromId(Convert.ToInt32(row["FNActionItemId"].ToString()));
var workingActionItemsTable = actionItemDAL.GetActionItemParamValues(Convert.ToInt32(row["FNActionItemId"].ToString()));
ivrCallsQueue.Enqueue(workingActionItemsTable);
}
StartCalls();
while (_ivrCallers.Count != 0)
{
testurls = testurls;
}
}
private void StartCalls()
{
int maxLines = 5;
if (_ivrCallsQueue.Count < maxLines)
{
maxLines = _ivrCallsQueue.Count;
}
for (int i = 0; i < maxLines; i++)
{
DataTable workingCall = new DataTable();
_ivrCallsQueue.TryDequeue(out workingCall);
BackgroundWorker ivrCaller = new BackgroundWorker();
_ivrCallers.Add(ivrCaller);
ivrCaller.DoWork += delegate(object sender, DoWorkEventArgs e)
{
RequestIVR(workingCall, Convert.ToInt32(workingCall.Rows[2][0].ToString()));
_ivrCallers.Remove(ivrCaller);
};
ivrCaller.RunWorkerCompleted += (bw_AnalyzeResults);
ivrCaller.RunWorkerAsync();
}
}
private void bw_AnalyzeResults(object sender, RunWorkerCompletedEventArgs e)
{
DataTable workingCall = new DataTable();
if (_ivrCallsQueue.Count != 0)
{
_ivrCallsQueue.TryDequeue(out workingCall);
BackgroundWorker ivrCaller = new BackgroundWorker();
ivrCaller.DoWork += delegate(object completeSender, DoWorkEventArgs completeArgs)
{
RequestIVR(workingCall, Convert.ToInt32(workingCall.Rows[2][0].ToString()));
_ivrCallers.Remove(ivrCaller);
};
ivrCaller.RunWorkerCompleted += (bw_AnalyzeResults);
ivrCaller.RunWorkerAsync();
}
else
{
}
}
private void RequestIVR(DataTable workingTable,int fnActionItemID)
{
var urlRequest = "http://uccx_http_trigger:9080/test?strTestMode=1&strTaskID=" + fnActionItemID;
var webClient = new WebClient { UseDefaultCredentials = true, Proxy = WebRequest.DefaultWebProxy };
DecodeResponseType(GetValueFromElement("Response Code was ", webClient.DownloadString(urlRequest)));
}
This will spawn at most five threads that each attempt to pull the next item from the queue and process it. If the queue is empty the attempt will fail and the thread will simply exit:
private List<System.Threading.Thread> Threads = new List<System.Threading.Thread>();
private ConcurrentQueue<DataTable> _ivrCallsQueue = new ConcurrentQueue<DataTable>();
private void StartCalls()
{
int maxLines = Math.Min(5 , _ivrCallsQueue.Count);
for (int i = 0; i < maxLines; i++ )
{
System.Threading.Thread T = new System.Threading.Thread(delegate()
{
DataTable workingCall;
while (_ivrCallsQueue.TryDequeue(out workingCall))
{
RequestIVR(workingCall, Convert.ToInt32(workingCall.Rows[2][0].ToString()));
}
});
Threads.Add(T);
T.Start();
}
}
The threads will keep running until all the items have been processed.
It looks like bw_AnalyzeResults does pretty much the same thing that StartCalls() does. In other words, when the background worker has finished its work, you immediately enqueue the same work to happen again, recursively forever?
By the looks of it, you want bw_AnalyzeResults to analyze the results returned by calling your web service. That is not what is happening at the moment.
The code below taken from the bw_AnalyzeResults event handler is scheduling a background job and making itself handle the RunWorkerCompleted event. So, presumably the software keeps going around and around executing bw_AnalyzeResults forever until you kill the process?
private void bw_AnalyzeResults(object sender, RunWorkerCompletedEventArgs e)
{
ivrCaller.DoWork += delegate(object completeSender, DoWorkEventArgs completeArgs)
{
RequestIVR(workingCall, Convert.ToInt32(workingCall.Rows[2][0].ToString()));
_ivrCallers.Remove(ivrCaller);
};
ivrCaller.RunWorkerCompleted += (bw_AnalyzeResults);
}
I have my application in which in three datagridview independently in three thread load data from wcf service. I execute in each thread timer which every second load this data.
My problem is that every time my thread go threw each thread but only like I show in method timerNowyYork_Elapsed
Any idea why this happens ? I bad lock thread?
this code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
namespace Sprawdzanie_warunków_pogodowych
{
public partial class Form1 : Form
{
PogodaEntities entity = new PogodaEntities();
System.Timers.Timer timerKrakow = new System.Timers.Timer();
System.Timers.Timer timerSzczecin = new System.Timers.Timer();
System.Timers.Timer timerNowyYork = new System.Timers.Timer();
KeyValuePair<string, string> krakowInfo;
KeyValuePair<string, string> szczecinInfo;
KeyValuePair<string, string> nowyYorkInfo;
public Form1()
{
System.Net.ServicePointManager.Expect100Continue = false;
InitializeComponent();
List<MiastoContainer> miasta = (from miasto in entity.Miasta
select new MiastoContainer()
{
MiastoName = miasto.Nazwa,
Panstwo = miasto.Państwo
}).ToList();
krakowInfo = new KeyValuePair<string, string>(miasta[0].MiastoName, miasta[0].Panstwo);
szczecinInfo = new KeyValuePair<string, string>(miasta[1].MiastoName, miasta[1].Panstwo);
nowyYorkInfo = new KeyValuePair<string, string>(miasta[2].MiastoName, miasta[2].Panstwo);
ParameterizedThreadStart ptsKrakow = new ParameterizedThreadStart(PobierzKrakow);
Thread tKrakow = new Thread(ptsKrakow);
tKrakow.Start(this.dataGridViewKrakow);
ParameterizedThreadStart ptsSzczecin = new ParameterizedThreadStart(PobierzSzczecin);
Thread tSzczecin = new Thread(ptsSzczecin);
tSzczecin.Start(this.dataGridViewSzczecin);
}
private void oAutorzeToolStripMenuItem_Click(object sender, EventArgs e)
{
new AboutBox1().Show();
}
private void zapiszRaportToolStripMenuItem_Click(object sender, EventArgs e)
{
}
public void PobierzKrakow(object parameters)
{
this.timerKrakow.Elapsed += new System.Timers.ElapsedEventHandler(timerKrakow_Elapsed);
this.timerKrakow.Enabled = true;
this.timerKrakow.Interval = 1000;
this.timerKrakow.Start();
}
public void PobierzSzczecin(object parameters)
{
this.timerSzczecin.Elapsed += new System.Timers.ElapsedEventHandler(timerSzczecin_Elapsed);
this.timerSzczecin.Enabled = true;
this.timerSzczecin.Interval = 1000;
this.timerSzczecin.Start();
}
public void PobierzNowyYork(object parameters)
{
this.timerNowyYork.Elapsed += new System.Timers.ElapsedEventHandler(timerNowyYork_Elapsed);
this.timerNowyYork.Enabled = true;
this.timerNowyYork.Interval = 1000;
this.timerNowyYork.Start();
}
void timerNowyYork_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{ GlobalWeather.Weather weather = new GlobalWeather.Weather();
lock (weather)
{
//thread always start from here
List<object> weatherList = new List<object>();
weatherList.Add(weather.GetTempreature(nowyYorkInfo.Key, nowyYorkInfo.Value));
//and end here , never come any line further
weatherList.Add(weather.GetPressure(nowyYorkInfo.Key, nowyYorkInfo.Value));
weatherList.Add(weather.GetHumidity(nowyYorkInfo.Key, nowyYorkInfo.Value));
weatherList.Add(weather.GetVisibility(nowyYorkInfo.Key, nowyYorkInfo.Value));
entity.SaveChanges();
WarunkiPogodowe warunki = new WarunkiPogodowe()
{
Temperatura = weatherList[0].ToString(),
Ciśnienie = weatherList[1].ToString(),
Wilgotność = weatherList[2].ToString(),
Widoczność = weatherList[3].ToString(),
DataSprawdzenia = DateTime.Now
};
entity.AddToWarunkiPogodowe(warunki);
entity.SaveChanges();
int miastoId = entity.Miasta.First(m => m.Nazwa == nowyYorkInfo.Key).id;
Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
{
idMiasto_FK = miastoId,
idWarunkiPogodowe_FK = warunki.id
};
entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
entity.SaveChanges();
this.dataGridViewNowyYork.Rows.Add(warunki);
}
}
void timerSzczecin_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
GlobalWeather.Weather weather = new GlobalWeather.Weather();
lock (weather)
{
List<object> weatherList = new List<object>();
weatherList.Add(weather.GetTempreature(szczecinInfo.Key, szczecinInfo.Value));
weatherList.Add(weather.GetPressure(szczecinInfo.Key, szczecinInfo.Value));
weatherList.Add(weather.GetHumidity(szczecinInfo.Key, szczecinInfo.Value));
weatherList.Add(weather.GetVisibility(szczecinInfo.Key, szczecinInfo.Value));
entity.SaveChanges();
WarunkiPogodowe warunki = new WarunkiPogodowe()
{
Temperatura = weatherList[0].ToString(),
Ciśnienie = weatherList[1].ToString(),
Wilgotność = weatherList[2].ToString(),
Widoczność = weatherList[3].ToString(),
DataSprawdzenia = DateTime.Now
};
entity.AddToWarunkiPogodowe(warunki);
entity.SaveChanges();
int miastoId = entity.Miasta.First(m => m.Nazwa == szczecinInfo.Key).id;
Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
{
idMiasto_FK = miastoId,
idWarunkiPogodowe_FK = warunki.id
};
entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
entity.SaveChanges();
this.dataGridViewSzczecin.Rows.Add(warunki);
}
}
void timerKrakow_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
GlobalWeather.Weather weather = new GlobalWeather.Weather();
lock (weather)
{
List<object> weatherList = new List<object>();
weatherList.Add(weather.GetTempreature(krakowInfo.Key, krakowInfo.Value));
weatherList.Add(weather.GetPressure(krakowInfo.Key, krakowInfo.Value));
weatherList.Add(weather.GetHumidity(krakowInfo.Key, krakowInfo.Value));
weatherList.Add(weather.GetVisibility(krakowInfo.Key, krakowInfo.Value));
entity.SaveChanges();
WarunkiPogodowe warunki = new WarunkiPogodowe()
{
Temperatura = weatherList[0].ToString(),
Ciśnienie = weatherList[1].ToString(),
Wilgotność = weatherList[2].ToString(),
Widoczność = weatherList[3].ToString(),
DataSprawdzenia = DateTime.Now
};
entity.AddToWarunkiPogodowe(warunki);
entity.SaveChanges();
int miastoId = entity.Miasta.First(m => m.Nazwa == krakowInfo.Key).id;
Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
{
idMiasto_FK = miastoId,
idWarunkiPogodowe_FK = warunki.id
};
entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
entity.SaveChanges();
this.dataGridViewKrakow.Rows.Add(warunki);
}
}
}
class MiastoContainer
{
string miastoName;
public string MiastoName
{
get { return miastoName; }
set { miastoName = value; }
}
string panstwo;
public string Panstwo
{
get { return panstwo; }
set { panstwo = value; }
}
public MiastoContainer()
{ }
public MiastoContainer(string miasto, string panstwo)
{
this.MiastoName = miasto;
this.Panstwo = panstwo;
}
public void Add(MiastoContainer item)
{
((ICollection<MiastoContainer>)this).Add(item);
}
}
}
Your locks are completely useless. As you are locking on an object that you just created, each lock will have it's own identifier and does not affect each other at all.
You need all locks that should exclude each other to use the same object as identifier.
System.Timers.Timer lets you set the SynchronizingObject so that it will invoke the callback on the UI thread. When you create your timers, write:
this.timerKrakow.SynchronizingObject = this;
The timer's elapsed event will then be invoked on the UI thread. That eliminates the need for locks in your event handlers.
You could do the same thing, by the way, with a System.Windows.Forms.Timer, which always invokes the event handler on the UI thread.
The drawback to raising the event on the UI thread is that it might block the user interface. It depends on how much time is spent in the event handler. If your event handler is very quick, then this isn't a problem. If it will take 100 milliseconds to process the event handler, though, you probably don't want to do it on the UI thread.
If you elect not to do it on the UI thread, you need to synchronize access to the UI. The timer event handler can't just modify user interface elements. Instead, you need to call this.Invoke so that any UI modification is done on the UI thread.
I strongly suggest that you NOT use System.Timers.Timer. As the documentation states:
The Timer component catches and
suppresses all exceptions thrown by
event handlers for the Elapsed event.
This behavior is subject to change in
future releases of the .NET Framework.
In other words, if there is a bug in your event handler that throws an exception, you will never know it. I suggest using System.Windows.Forms.Timer or System.Threading.Timer instead.
I don't fully understand your question, but (unless I'm mistaken) the timer callbacks occur in the ThreadPool (or the GUI thread, dependent on usage), so starting them in different threads is pointless.
It seems to me that you are accessing DataGridView directly from another thread. You should not do that. UI controls must always be called from the UI thread. You can use the ISynchronizeInvoke interface to pass the data into correct thread.
this.dataGridViewNowyYork.Invoke(new Action(() => {
this.dataGridViewNowyYork.Rows.Add(warunki);
}), null);