|
我利用winform调用webservice,想在客户端实现异步访问(或者说多线程)。
我想有三种方式:
1、我用了代理类的异步访问方法和事件(GetMethodAsync和methodCompleted)。
在form的Button1_Click中调用wsClient.GetMethodAsync()开始异步访问webservice.在methodCompleted中利用参数获得webservice返回结果。然后绑定到窗体中实例化的datagrid中。这种方式是ok的.
代码片段:
private MyPubsService pubsService;webservice代理
private DataSet ds;
public Form1()
{
InitializeComponent();
pubsService = new MyPubsService();
pubsService.GetAuthorsCompleted += new GetAuthorsCompletedEventHandler(pubsService_GetAuthorsCompleted);
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
pubsService.Dispose();
}
void pubsService_GetAuthorsCompleted(object sender, GetAuthorsCompletedEventArgs e)
{
ds = (DataSet)e.Result;
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
private void button1_Click(object sender, EventArgs e)
{
pubsService.GetAuthorsAsync();
}*/
2、我想利用代理实体的BeginInvoke()和Endinvoke()方法以及回调函数来实现。
在回调函数中获得的dataset实体是没有问题的。但在回调函数中,利用
dataGrid1.datasource=ds.tables[0].defaultview;时,在运行时报异常
-----------线程间操作无效,从不是创建datagrid1控件的线程访问它。----
百思不得其解,请老师指教!
代码片段:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Web.Services;
using WinFormWebService.WS;
using System.Threading;
namespace WinFormWebService
{
public partial class Form1 : Form
{
ServerWebService wbSData;
private DataSet ds;
delegateBindData delg;
public Form1()
{
InitializeComponent();
wbSData = new ServerWebService();
delg = new delegateBindData(wbSData.GetBindData);
}
private void button1_Click(object sender, EventArgs e)
{
IAsyncResult ar = delg.BeginInvoke(new AsyncCallback(CallBackFn), delg);
}
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (wbSData.pubsService != null)
{
wbSData.pubsService.Dispose();
}
}
void CallBackFn(IAsyncResult ar)
{
delg = (delegateBindData)ar.AsyncState;
ds = delg.EndInvoke(ar);
dataGrid1.DataSource = ds.Tables[0].DefaultView;
}
public class ServerWebService
{
public MyPubsService pubsService;
public ServerWebService()
{
pubsService = new MyPubsService();
}
public DataSet GetBindData()
{
DataSet ds = pubsService.GetAuthors();
return ds;
}
}
public delegate DataSet delegateBindData();
}
3、利用常规的线程方法,thread.start()来进行异步访问。这种我没试。
|
|